【问题标题】:With both stacked and dodged bars, how can you remove dodge-bar elements from legend?使用堆叠条和闪避条,如何从图例中删除闪避条元素?
【发布时间】:2015-12-27 07:33:06
【问题描述】:

感谢combine stacked bars and dodged bars,我使用显示的数据框创建了下面的图。但是现在,由于轴标题为条形命名,除了一个堆叠条形之外,我如何删除图例元素?也就是图例可以只显示Big8 bar的段吗?

> dput(combo)
structure(list(firm = structure(c(12L, 1L, 11L, 13L, 2L, 3L, 
4L, 5L, 6L, 7L, 8L, 9L, 10L), .Label = c("Avg.", "Co", "Firm1", 
"Firm2", "Firm3", "Firm4", "Firm5", "Firm6", "Firm7", "Firm8", 
"Median", "Q1", "Q3"), class = "factor"), metric = structure(c(5L, 
1L, 4L, 6L, 3L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("Avg.", 
"Big8", "Co", "Median", "Q1", "Q3"), class = "factor"), value = c(0.0012, 
0.0065, 0.002, 0.0036, 0.0065, 0.000847004466666667, 0.000658907411111111, 
0.0002466389, 8.41422555555556e-05, 8.19149222222222e-05, 7.97185555555556e-05, 
7.82742555555556e-05, 7.56679888888889e-05), grp = structure(c(1L, 
2L, 3L, 6L, 4L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L), .Label = c("Q1", 
"Avg.", "Median", "Co", "Big8", "Q3"), class = "factor")), .Names = c("firm", 
"metric", "value", "grp"), row.names = c(NA, -13L), class = "data.frame")

这是绘图代码。

ggplot(combo, aes(x=grp, y=value, fill=firm)) + 
  geom_bar(stat="identity") +
  labs(x = "", y = "") +
  theme(legend.position = "bottom") +
  guides(fill = guide_legend(nrow = 2))

情节,理想情况下,图例中的元素集较少。

【问题讨论】:

    标签: r ggplot2 legend


    【解决方案1】:

    您可以为scale_fill_discrete手动设置breaks

    library(ggplot2)
    ggplot(combo, aes(x=grp, y=value, fill=firm)) + 
        geom_bar(stat="identity") +
        labs(x = "", y = "") +
        theme(legend.position = "bottom") +
        guides(fill = guide_legend(nrow = 2)) +
        scale_fill_discrete(breaks = combo$firm[combo$metric=="Big8"])
    

    我不能 100% 确定您要保留哪些标签,但手动输入的矢量 combo$firmcombo$metric 都可以。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-31
      • 1970-01-01
      • 2021-07-29
      • 1970-01-01
      • 1970-01-01
      • 2012-09-24
      • 1970-01-01
      相关资源
      最近更新 更多