繁体   English   中英

ggplot grouped geom_bar - 将因子类别的标签添加到 x 轴 label

[英]ggplot grouped geom_bar - adding labels of factor categories to the x-axis label

我有这个 R 代码来生成垂直分组条形图:

library(ggplot2)
exampledf <- data.frame(
  subchar = c("facebook", "twitter", "snapchat", "male", "female"),
  superchar = c("social media", "social media", "social media", "gender", "gender"),
  cweight = c(.2, .4, .4, .7, .3)
)

ggplot(exampledf, aes(x = superchar, y = cweight, fill = subchar)) +
  geom_bar(stat='identity', position = position_dodge()) +
  #scale_fill_manual(values = c(col.tint(color_in, .7), col.tint(color_in, .8), col.tint(color_in, .9), col.tint(color_in, 1))) +
  scale_fill_discrete()+
  coord_flip() +
  theme_minimal() +
  geom_text(aes(label = signif(cweight, digits=3)), position=position_dodge(width=0.9), hjust=.5, size=2.5)+
  theme(
    legend.position="none",
    axis.title.x=element_blank(),
    axis.title.y=element_blank(),
    axis.text.x=element_blank(),
    axis.ticks.y=element_blank(),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank()
  )

但是,我想在图表的此处添加“subchar”标签(在“superchar”label 的右侧,但在条形的左侧):带有位置的图形图像

有没有办法做到这一点?

superchar使用 faceting 并使subchar成为 x 轴美学:

ggplot(exampledf, aes(x=subchar, y = cweight, fill = subchar)) +
  geom_col() +
  geom_text(aes(label = signif(cweight, digits=3)), 
            position=position_stack(vjust=0.5), 
            size=3, colour="white")+
  theme_void() +
  theme(
    axis.text.y=element_text(size=10),
    strip.placement="outside",
    strip.text.y=element_text(angle=180, hjust=1, face="bold", size=11,
                              margin=margin(r=10))
  ) +
  coord_flip() +
  facet_grid(superchar ~ ., scales="free_y", space="free_y", switch="y") +
  scale_y_continuous(expand=c(0,0)) +
  guides(fill=FALSE)

在此处输入图像描述

需要您旋转标签以查看整个内容的 hacky 方法可以使用geom_text完成。 如果您已经需要考虑其他一些变量,我只会使用它。

library(ggplot2)
exampledf <- data.frame(
  subchar = c("facebook", "twitter", "snapchat", "male", "female"),
  superchar = c("social media", "social media", "social media", "gender", "gender"),
  cweight = c(.2, .4, .4, .7, .3)
)

ggplot(exampledf, aes(x = superchar, y = cweight, fill = subchar)) +
  geom_bar(stat = "identity", position = position_dodge()) +
  coord_flip() +
  theme_minimal() +
  geom_text(
    aes(label = signif(cweight, digits = 3)),
    position = position_dodge(width = 0.9),
    hjust = .5, size = 2.5
  ) +
  geom_text(
    aes(label = subchar, y = 0),
    position = position_dodge(width = 0.9),
    vjust = 1.5, size = 2.5, angle = -90
  ) +
  theme(
    legend.position = "none",
    axis.title.x = element_blank(),
    axis.title.y = element_blank(),
    axis.text.x = element_blank(),
    axis.ticks.y = element_blank(),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank()
  )

代表 package (v0.3.0) 于 2019 年 9 月 19 日创建

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM