【发布时间】: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 <- rbind(summarised_df,c("During","a",NA,NA), c("During","c",NA,NA)) -
示例数据已经过编辑,希望现在更清楚,谢谢。
-
关于颜色:看看
scale_fill_manual()