r - ggplot 分组 geom_bar - 将因子类别的标签添加到 x 轴标签

标签 r ggplot2 geom-bar

我有这个 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”标签的右侧,但在条形图的左侧):
Image of graph with location

有没有办法做到这一点?

最佳答案

superchar 使用刻面并制作 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)

enter image description here

关于r - ggplot 分组 geom_bar - 将因子类别的标签添加到 x 轴标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58016349/

相关文章:

r - 从多元 t 分布生成随机变量

r - 带有 rstudio-server 开源的 Jupyter 笔记本

r - 将强化的 data.frame 转换回 sf 对象

r - 如何在 R 中使用 ggplot/geom_bar 从数据集中添加自定义标签?

删除两个图例中的线条和背景

r - 将条形图绘制到 R ggplot2 中的 map

r - 如何从数据框中删除少于 5 个观察值的个体

r - 使用 ggplot2 的 stat_density_2d 仅显示高密度区域

r - 如何 : Automatically set fixed coordinate ratio (coord_fixed) when x- and y-axis are on different scales?

r - 用ggplot绘制表格对象?