ggplot 添加注释框,其中包含动态值的箭头
ggplot add annotation box, arrow with dynamic value in it
我正在尝试在绘图中添加注释框(使用 ggplot)。我在注释中使用文本几何添加了文本。逻辑应该是——每次我们生成图表时,它都应该有包含最新月份和值的文本框。文本框应使用箭头或线指向图中的相应值。这是我到目前为止尝试过的方法,
myplot <- ggplot(sa_dat1, aes(x = variable, y = value )) +
theme_minimal() +
geom_line(linetype = "solid", color = "#0072CE",size=1) +
geom_smooth(method="loess", se=FALSE , linetype = "dashed", color="black", size = 0.5) +
scale_x_date(labels = date_format("%b-%Y"), date_breaks ="2 month",expand = c(0.005,0)) +
theme(axis.text.x = element_text(angle = 90, hjust = 1,vjust=0.5)) +
scale_y_continuous(limits=c(ylimitmin5,ylimitmax5), labels=dollar_format(prefix="$"),
breaks = seq(ylimitmin5, ylimitmax5, by = 10000),
expand = c(0,0)) +
annotate("text", x=floor_date(max(sa_dat1$variable), "month") - months(12),
y= max(sa_dat1$value) - 20000, label = paste0("April 2017\n",
paste("$",round(max(sa_dat1$value)))))
这就是我得到的,
我的目标是这个,我不知道如何在我的文本周围添加箭头和文本框。
来自以上评论:
annotate(geom = "label", ...)
instead of "text"
gets you a box around the text that you can modify with fill, border, etc.
Just a shot in the dark, not tested: +annotate("segment", x=floor_date(max(sa_dat1$variable), "month") - months(12), xend = floor_date(max(sa_dat1$variable), "month"), y= max(sa_dat1$value) - 20000, yend= max(sa_dat1$value), arrow = arrow())
最后,您可以使用 x
和 y
美学值调整箭头的起点和终点,就像您已经为标签调整了它们一样。也许试试 -months(8)
和 -10000
.
编辑添加:
- 调用
library(lubridate)
以使用 months()
和 floor_date()
我正在尝试在绘图中添加注释框(使用 ggplot)。我在注释中使用文本几何添加了文本。逻辑应该是——每次我们生成图表时,它都应该有包含最新月份和值的文本框。文本框应使用箭头或线指向图中的相应值。这是我到目前为止尝试过的方法,
myplot <- ggplot(sa_dat1, aes(x = variable, y = value )) +
theme_minimal() +
geom_line(linetype = "solid", color = "#0072CE",size=1) +
geom_smooth(method="loess", se=FALSE , linetype = "dashed", color="black", size = 0.5) +
scale_x_date(labels = date_format("%b-%Y"), date_breaks ="2 month",expand = c(0.005,0)) +
theme(axis.text.x = element_text(angle = 90, hjust = 1,vjust=0.5)) +
scale_y_continuous(limits=c(ylimitmin5,ylimitmax5), labels=dollar_format(prefix="$"),
breaks = seq(ylimitmin5, ylimitmax5, by = 10000),
expand = c(0,0)) +
annotate("text", x=floor_date(max(sa_dat1$variable), "month") - months(12),
y= max(sa_dat1$value) - 20000, label = paste0("April 2017\n",
paste("$",round(max(sa_dat1$value)))))
这就是我得到的,
我的目标是这个,我不知道如何在我的文本周围添加箭头和文本框。
来自以上评论:
annotate(geom = "label", ...)
instead of"text"
gets you a box around the text that you can modify with fill, border, etc.Just a shot in the dark, not tested:
+annotate("segment", x=floor_date(max(sa_dat1$variable), "month") - months(12), xend = floor_date(max(sa_dat1$variable), "month"), y= max(sa_dat1$value) - 20000, yend= max(sa_dat1$value), arrow = arrow())
最后,您可以使用 x
和 y
美学值调整箭头的起点和终点,就像您已经为标签调整了它们一样。也许试试 -months(8)
和 -10000
.
编辑添加:
- 调用
library(lubridate)
以使用months()
和floor_date()