【问题标题】:Changing legend properties in ggplot2更改 ggplot2 中的图例属性
【发布时间】:2015-09-28 11:31:07
【问题描述】:

我对 ggplot2 比较陌生,想知道是否有一种简单的方法可以更改图例。我在我的数据框中添加了一个虚拟变量(在下面的示例中为 AEmpty),它解释了在上一个答案 Control column widths in a ggplot2 graph with a series and inconsistent data 之后奇数个因素的间距和条形宽度。这似乎是最简单的方法 - 尽管欢迎提出可能解决替代方法的评论或答案!

所以在下面的示例中,我得到了一个如下所示的绘图输出。

我的问题是(1)有没有办法从“之后”中选择灰度,从而最大限度地提高显示条之间的颜色对比度? (2) 传说中的AEmpty怎么去掉?我在这里看到了一个类似的问题How do I manually change the key labels in a legend in ggplot2,但这里的答案不起作用,因为我已经在其他地方应用了填充功能,而 scale_fill_discrete 不起作用。

此外,如果有人知道缩放 x 轴因子的更简单方法,从而消除对这个“虚拟”变量的需要,我们将不胜感激。最终,所需的输出是一个条形图,其中每个条形具有相等的宽度,并且 x 轴上的每个“站点”间隔相等,只有相关因素显示在键中。

library(ggplot2)
#Create data
when <- as.factor(c(rep(c("Before","After"),each = 3),
      rep("During", 2),"AEmpty"))
site <- as.factor(c(rep(c("a","b","c"), 2),
      "b","a","c"))
mean <- c(6,4.5,4.5,1.75,3.25,2.5,3,0,0)
std_error <- c(2.31,1.04,0.5,0.63,1.70,1.32,1.53,NA,NA)
df <- data.frame(when,site,mean,std_error)
#Plot 
limits <- aes(ymax = mean + std_error, ymin=mean-std_error)
g <- ggplot(df, aes(site,mean,fill=when)) + geom_bar(stat = "identity", position = position_dodge()) + geom_errorbar(limits, width = 0.25, position = position_dodge(width = 0.9)) + scale_fill_grey()
g 

【问题讨论】:

  • 提供简单的可重现示例或数据集的一部分
  • 将你的假人创建改为:summarised_df &lt;- rbind(summarised_df,c("During","a",NA,NA), c("During","c",NA,NA))
  • 示例数据已经过编辑,希望现在更清楚,谢谢。
  • 关于颜色:看看scale_fill_manual()

标签: r ggplot2


【解决方案1】:

我不完全确定您的意思:“我已经在其他地方应用了填充功能”。由于fill 在每个图表中只能出现一次,您可以将breakslabels 合并到您未在此处显示的“其他填充功能”中。

对于您提供的示例,下面的代码可以满足您的需求:

library(ggplot2)
# Create data
when <- as.factor(c(rep(c("Before","After"),each = 3),
                    rep("During", 2),"AEmpty"))
site <- as.factor(c(rep(c("a","b","c"), 2),
                    "b","a","c"))
mean <- c(6,4.5,4.5,1.75,3.25,2.5,3,0,0)
std_error <- c(2.31,1.04,0.5,0.63,1.70,1.32,1.53,NA,NA)
df <- data.frame(when,site,mean,std_error)

# Plot 
limits <- aes(ymax = mean + std_error, ymin=mean-std_error)

ggplot(df, aes(site,mean,fill=when)) +
  geom_bar(stat = "identity", position = position_dodge()) +
  geom_errorbar(limits, width = 0.25, position = position_dodge(width = 0.9)) +
  scale_fill_manual(values = c("AEmpty" = "grey1",
                               "After" = "grey15",
                               "Before" = "grey55",
                               "During" = "grey75"),
                    breaks = c("After", "Before", "During"),
                    labels = c("After", "Before", "During")) 

要选择灰色阴影,请咨询this list of R-colours

【讨论】:

    猜你喜欢
    • 2020-05-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-27
    • 2015-07-11
    • 2013-03-06
    • 2020-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多