[英]R ggplot annotate line plot with max value
I have a line plot created with this code:我有一行 plot 使用此代码创建:
# Create data
year <- c(2006,2007,2008,2009,2010,2011,2012,2013,2014)
sales <- c(4176,8560,6473,10465,14977,15421,14805,11183,10012)
df <- data.frame(year,sales)
# Plot
ggplot(data = df,aes(year, sales),group = 1) + geom_point() + geom_line()
I would like to annotate it with a line that "shows" the maximum value like the example below:我想用“显示”最大值的行来注释它,如下例所示:
Is this possible with ggplot? ggplot可以吗?
Yes.是的。 For your current example, try this:
对于您当前的示例,请尝试以下操作:
ggplot(data = df,aes(year, sales),group = 1) + geom_point() + geom_line() +
geom_segment(aes(x = 2011, y = 0, xend = 2011, yend = 15421),linetype="dashed", color = "red")
Of course, for more general plotting needs, you can improve the codes instead of manually inputting the values here.当然,对于更一般的绘图需求,您可以改进代码而不是在这里手动输入值。
This is close, just needs the arrow:这很接近,只需要箭头:
ggplot(data = df,aes(year, sales),group = 1) + geom_point() + geom_line() + theme_bw() +
geom_linerange(aes(ymax=sales, ymin=min(df$sales)),
data=df[which.max(df$sales),],
col="red", lty=2) +
geom_text(aes(label=sales),data=df[which.max(df$sales),], hjust=1.2, vjust=3)
It works by adding geom_linerange
and geom_text
geoms but setting the data for each to be the row of the original dataset corresponding to the maximum of the 'sales' column.它通过添加
geom_linerange
和geom_text
几何但将每个数据设置为原始数据集对应于“销售”列的最大值的行来工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.