与 ggplotly() 结合使用时,ggplot2 堆叠条似乎被分成许多不同的切片
Posted
技术标签:
【中文标题】与 ggplotly() 结合使用时,ggplot2 堆叠条似乎被分成许多不同的切片【英文标题】:ggplot2 stacked bars seem to be separated in many different slices when combined with ggplotly() 【发布时间】:2021-11-09 16:16:45 【问题描述】:我在下面创建了堆积条形图,但是虽然代码似乎可以工作,但条形图似乎被分成多个切片,每个切片都有不同的悬停,这是不必要且令人困惑的。如何删除它们?
Tar2<-structure(list(Site = c("ABC123", "ABC123", "ABC123", "ABC123",
"ABC123", "ABC123", "ABC123", "ABC123", "ABC123", "ABC123", "ABC123",
"ABC123", "ABC123", "ABC123", "ABC123", "ABC123", "ABC123", "ABC123",
"ABC123", "ABC123", "ABC123", "ABC123", "ABC123", "ABC123", "ABC123",
"ABC123", "ABC123", "ABC123", "ABC123", "ABC123", "ABC123", "ABC123",
"ABC123", "ABC123", "ABC123", "ABC123", "ABC123", "ABC123", "ABC123",
"ABC123"), Group = c("A", "A", "B", "B", "A", "A", "A", "A",
"B", "B", "B", "B", "B", "B", "B", "B", "B", "B", "B", "B", "B",
"B", "A", "A", "B", "B", "B", "B", "A", "A", "B", "B", "B", "B",
"B", "B", "B", "B", "A", "A"), Patients = c(46L, 46L, 46L, 46L,
46L, 46L, 46L, 46L, 46L, 46L, 46L, 46L, 46L, 46L, 46L, 46L, 46L,
46L, 46L, 46L, 46L, 46L, 46L, 46L, 46L, 46L, 46L, 46L, 46L, 46L,
46L, 46L, 46L, 46L, 46L, 46L, 46L, 46L, 46L, 46L)), row.names = c(NA,
-40L), class = c("tbl_df", "tbl", "data.frame"))
library(ggplot2)
library(dplyr)
library(plotly)
c<-ggplot(Tar2, aes(fill=Group, y=Patients, x=Site)) +
geom_bar(position="stack", stat="identity")
c<-c+ theme(axis.text.x = element_text(angle = 45, vjust = 0.5, hjust=1))+labs(title = "Figure 2:Weekly Enrollment by Cohort by Site"
)
ggplotly(c)
【问题讨论】:
【参考方案1】:您可以使用group_by
和slice
来获得每组仅一行:
Tar2 <- structure(list(Site = c(
"ABC123", "ABC123", "ABC123", "ABC123",
"ABC123", "ABC123", "ABC123", "ABC123", "ABC123", "ABC123", "ABC123",
"ABC123", "ABC123", "ABC123", "ABC123", "ABC123", "ABC123", "ABC123",
"ABC123", "ABC123", "ABC123", "ABC123", "ABC123", "ABC123", "ABC123",
"ABC123", "ABC123", "ABC123", "ABC123", "ABC123", "ABC123", "ABC123",
"ABC123", "ABC123", "ABC123", "ABC123", "ABC123", "ABC123", "ABC123",
"ABC123"
), Group = c(
"A", "A", "B", "B", "A", "A", "A", "A",
"B", "B", "B", "B", "B", "B", "B", "B", "B", "B", "B", "B", "B",
"B", "A", "A", "B", "B", "B", "B", "A", "A", "B", "B", "B", "B",
"B", "B", "B", "B", "A", "A"
), Patients = c(
46L, 46L, 46L, 46L,
46L, 46L, 46L, 46L, 46L, 46L, 46L, 46L, 46L, 46L, 46L, 46L, 46L,
46L, 46L, 46L, 46L, 46L, 46L, 46L, 46L, 46L, 46L, 46L, 46L, 46L,
46L, 46L, 46L, 46L, 46L, 46L, 46L, 46L, 46L, 46L
)), row.names = c(
NA,
-40L
), class = c("tbl_df", "tbl", "data.frame"))
library(tidyverse)
c <-
Tar2 %>%
group_by(Group, Patients, Site) %>%
slice(1) %>%
ggplot(aes(fill = Group, y = Patients, x = Site)) +
geom_bar(position = "stack", stat = "identity") +
theme(axis.text.x = element_text(angle = 45, vjust = 0.5, hjust = 1)) +
labs(title = "Figure 2:Weekly Enrollment by Cohort by Site")
c
由reprex package (v2.0.1) 于 2021-09-14 创建
【讨论】:
以上是关于与 ggplotly() 结合使用时,ggplot2 堆叠条似乎被分成许多不同的切片的主要内容,如果未能解决你的问题,请参考以下文章