向 ggplot 添加文本
Add text to ggplot
(更新)
我有这样的 ggplot,但是 x 轴日期按比例缩放:
g1 <- ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar()
在两个柱上方(比如说 VS2
和 IF
,但在我的图表中它是一个日期)我想在柱上方 13.000 处放置一个文本标签。
我尝试了很多东西,但这是最接近的:
这是我在我的图表中用日期轴尝试的
g1 + geom_text(aes(as.Date("2014-10-05"), 13000), label="boat")
但这只会向图中添加一个,并且一旦我尝试扩展它,例如
g1 + geom_text(aes(c(as.Date("2014-10-05"),as.Date("2014-10-20")) , 13000), label=c("boat", "train"))
然后我得到错误:
Error: Aesthetics must either be length one, or the same length as the
dataProblems:c(as.Date("2014-10-05"), as.Date("2014-10-20"))
我还尝试从数据框 (oefen
) 中读取文本和标签,其中我使用了与原始图相同的名称
g1 + geom_text(data=oefen, aes(x=newdat, y=Number, label=oefen$labs, fill=1))
我收到错误
Error: Continuous value supplied to discrete scale
我尝试了许多其他解决方案,但找不到答案。我错过了什么?
考虑使用 annotate()
在绘图的给定位置放置任何文本。因子变量,如 x 轴上的清晰度因子,每个级别都有一个数字,因此您可以使用该数字来定位文本。我假设日期变量具有相同的用法。:
ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar() +
annotate("text", x=8, y=13000, label= "boat") +
annotate("text", x = 4, y=13000, label = "ship")
评论后编辑
为了效率,可以把注解组合起来,比如这样:
ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar() +
annotate("text", x = c(2,4,6,8), y=13000, label = c("two", "ship", "six", "boat"))
尝试使用以下方法:
在数字或点后使用文本 Before
在 geom_text(paste0( percent, "%"))
中使用后,它看起来像这样
After
(更新) 我有这样的 ggplot,但是 x 轴日期按比例缩放:
g1 <- ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar()
在两个柱上方(比如说 VS2
和 IF
,但在我的图表中它是一个日期)我想在柱上方 13.000 处放置一个文本标签。
我尝试了很多东西,但这是最接近的:
这是我在我的图表中用日期轴尝试的
g1 + geom_text(aes(as.Date("2014-10-05"), 13000), label="boat")
但这只会向图中添加一个,并且一旦我尝试扩展它,例如
g1 + geom_text(aes(c(as.Date("2014-10-05"),as.Date("2014-10-20")) , 13000), label=c("boat", "train"))
然后我得到错误:
Error: Aesthetics must either be length one, or the same length as the dataProblems:c(as.Date("2014-10-05"), as.Date("2014-10-20"))
我还尝试从数据框 (oefen
) 中读取文本和标签,其中我使用了与原始图相同的名称
g1 + geom_text(data=oefen, aes(x=newdat, y=Number, label=oefen$labs, fill=1))
我收到错误
Error: Continuous value supplied to discrete scale
我尝试了许多其他解决方案,但找不到答案。我错过了什么?
考虑使用 annotate()
在绘图的给定位置放置任何文本。因子变量,如 x 轴上的清晰度因子,每个级别都有一个数字,因此您可以使用该数字来定位文本。我假设日期变量具有相同的用法。:
ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar() +
annotate("text", x=8, y=13000, label= "boat") +
annotate("text", x = 4, y=13000, label = "ship")
评论后编辑
为了效率,可以把注解组合起来,比如这样:
ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar() +
annotate("text", x = c(2,4,6,8), y=13000, label = c("two", "ship", "six", "boat"))
尝试使用以下方法: 在数字或点后使用文本 Before
在 geom_text(paste0( percent, "%"))
中使用后,它看起来像这样
After