[英]R ggplot annotate line plot with max value
我有一行 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()
我想用“显示”最大值的行来注释它,如下例所示:
ggplot可以吗?
是的。 对于您当前的示例,请尝试以下操作:
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")
当然,对于更一般的绘图需求,您可以改进代码而不是在这里手动输入值。
这很接近,只需要箭头:
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)
它通过添加geom_linerange
和geom_text
几何但将每个数据设置为原始数据集对应于“销售”列的最大值的行来工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.