我想添加一个图例我的情节,但我有不同的美学,我从来没有创建一个传奇,所以我觉得很难确定如何建立它。添加传说到ggplot直方图与不同类型的美学
我的美学之一是填充代码,我手动添加为矢量。另一种美学是我用geom_vline添加的垂直线。
从下面的图表中,我要添加到图例中的三个特征:1)带深蓝色条纹,2)带浅蓝色条纹和3)垂直线条。
有没有人对我如何有效地编码这个建议?
#df
df <- data.frame(Time_Diff <- runif(1000, 0, 200))
# Show median, IQR range and outliers
colors <- c(rep("blue",3), rep("paleturquoise2",38))
bp_overall <- ggplot(data = df, aes(Time_Diff))
bp_overall +
geom_histogram(binwidth = 5, fill = colors) + #create histogram
ggtitle("Time Difference") +
xlab("Time in Days") +
ylab("Amount") +
geom_vline(xintercept = 3, linetype = "twodash", size = 1, colour= "darkblue") + #show median
scale_x_continuous(breaks = seq(0, 202, 10)) +
theme_light() +
theme(panel.grid.minor = element_blank(),
panel.border = element_blank(), #remove all border lines
axis.line.x = element_line(size = 0.5, linetype = "solid", colour = "black"), #add x-axis border line
axis.line.y = element_line(size = 0.5, linetype = "solid", colour = "black")) + #add y-axis border line
theme(plot.title = element_text(family = windowsFont("Verdana"), color="black", size=14, hjust = 0.5)) +
theme(axis.title = element_text(family = windowsFont("Verdana"), color="black", size=12))
经过朱克的建议,我来到了下面的脚本,该脚本很有效,我很满意。我现在唯一想做的事情就是让传奇成为一个整体(直方图传奇和线传奇组合成一个连贯的整体)。任何人都有一个建议?
# reformat data
set.seed(1)
df <- data.frame(runif(1000, 0, 200))
colnames(df) <- "Time_Diff"
bp_overall +
geom_histogram(data = subset(df, Time_Diff <= 12.5), aes(x = Time_Diff, fill="BAR BLUE"), binwidth = 5) + # subset for blue data, where aes fill is fill group 1 label
geom_histogram(data = subset(df, Time_Diff > 12.5), aes(x = Time_Diff, fill="BAR TURQUOISE"), binwidth = 5) + # subset for turquoise data, where aes fill is fill group 2 label
scale_fill_manual("Histogram Legend", values=c("blue", "paleturquoise2")) + # manually assign histogram fill colors
geom_vline(aes(xintercept = 3, colour="LINE DARK BLUE"), linetype="twodash", size = 1) + # where aes colour is vline label
scale_colour_manual("Line Legend", values="darkblue") + #removed legend title
scale_x_continuous(breaks = seq(0, 202, 10)) +
ggtitle("Time Difference") +
xlab("Time in Days") +
ylab("Amount") +
theme_light() +
theme(panel.grid.minor = element_blank(),
panel.border = element_blank(),
axis.line.x = element_line(size = 0.5, linetype = "solid", colour = "black"),
axis.line.y = element_line(size = 0.5, linetype = "solid", colour = "black"),
legend.position = c(0.95, 0.95),
legend.justification = c("right", "top"),
legend.box.just = ("right"))
最简单的方法使用
legend.margin
在顶部边缘和底部得到这个图例是指定'aes()'内部的特征。因此,你必须改变你的data.frame包括统计数据和一列的颜色。参见[这里](http://www.cookbook-r。com/Graphs/Legends_(ggplot2)/)或[这里](https://stackoverflow.com/questions/24932940/ggplot-does-not-show-legend-in-geom-histogram) – Jimbou@Jimbou我想我明白你的意思是转换数据帧。我已经在我的问题中完成了这些(请参阅解决方案概念的代码),但我无法弄清楚如何调整ggplot图中的代码。 – SHW