我想在图中添加一些自定义线。
我制作该图的MWC为:
df_tra %>%
filter(Theta_param==1, Int_dis=='Bench', Gamma_param==0.76, Rho_param==0) %>%
ggplot(aes(x = Debt))+
geom_line(aes(y = Gini_tra, colour = "Gini Coeff."), size = 1.2, colour="blue") +
xlab("Public Debt") +
ylab("Wealth Inequality") +
geom_hline(yintercept=1, linetype="dashed", color = "black")+
geom_vline(xintercept = 0.02, linetype="dashed",
color = "black")+
theme_minimal()+
在上面的代码中,我如何在图形中引入自定义线,其中这些线上方有一些文本:
例如,我打算做的事情应该看起来像这样:
答案 0 :(得分:1)
根据OP评论进行了更新
首先,使用示例数据的两个不同选项。由于您未包含df_tra对象,因此您的MWC无法正常工作,我使用了annotate
帮助中的mtcars数据集
这是使用ggplot2
库中的annotate的解决方案
ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point() +
annotate("text", x = 4, y = 25, label = "Some text") +
annotate("segment", x = 3.45, xend = 4.25, y = 19.5, yend = 25,
colour = "blue", arrow=arrow(ends = "last"))
# from arrow help:
# arrow(angle = 30, length = unit(0.25, "inches"),
# ends = "last", type = "open")
# Arguments
#
# angle
# The angle of the arrow head in degrees (smaller numbers
# produce narrower, pointier arrows). Essentially describes
# the width of the arrow head.
# length
# A unit specifying the length of the arrow head (from tip to base).
# ends
# One of "last", "first", or "both", indicating which ends of the line
# to draw arrow heads.
# type
# One of "open" or "closed" indicating whether the arrow head
# should be a closed triangle.
在ends="last
(默认)下,箭头的箭头位于x.end=
和y.end=
定义的点,在ends="first
下,箭头的箭头位于{{ 1}}和x=
。 y=
显示两个箭头。
其他选项将结合ends="both
和annotate
,如本post
geom_segment
首先模拟数据
ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point() +
annotate("text", x = 4, y = 25, label = "Some text") +
geom_segment(aes(x = 3.45, xend = 4.25, y = 19.5, yend = 25),
colour = "blue",
arrow=arrow(ends = "last"))
使用x <- seq(-5,10,0.5)
y <- 10*x^2 + 10*x - 100
df <- data.frame(x=x, y=y)
生成箭头来生成图的代码。我之所以选择此选项,是因为至少在我的计算机中,箭头看起来比annotate
生成的箭头更好。
geom_segment
和情节