将文本添加到 ggplot [英] Add text to ggplot

查看:60
本文介绍了将文本添加到 ggplot的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(更新)我有这样的ggplot,但是x轴日期缩放:

(updated) I have ggplot like this, but then the x axis Date scaled:

g1 <- ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar()

在两个条形图上方(比如说 VS2IF,但在我的图表中它是一个日期)我想在高度为 13.000 的条形图上方放置一个文本标签.

Above two bars (lets say VS2 and IF, but in my graph it is a date) I want to put a text label above the bars at height 13.000.

我尝试了很多东西,但这是最接近的:这是我用日期轴在我的图表中尝试的g1 + geom_text(aes(as.Date("2014-10-05"), 13000), label="boat")

I tried a lot of things, but this is what came closest: This is what I tried in my graph with the Date axis g1 + geom_text(aes(as.Date("2014-10-05"), 13000), label="boat")

但这只会在图表中添加一个,并且一旦我尝试扩展它,例如使用

but this adds only one to the graph and as soon as I try to extend it, for example with

g1 + geom_text(aes(c(as.Date("2014-10-05"),as.Date("2014-10-20")) , 13000), label=c("boat", "train"))

然后我得到错误:

错误:美学长度必须为 1,或与数据问题:c(as.Date("2014-10-05"), as.Date("2014-10-20"))

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) 中读取文本和标签,其中我使用了与原始图相同的名称

I also tried to read the text and labels from a dataframe (oefen), where I used the same names as the original plot

g1 + geom_text(data=oefen, aes(x=newdat, y=Number, label=oefen$labs, fill=1))

我得到了错误

错误:提供给离散刻度的连续值

Error: Continuous value supplied to discrete scale

我尝试了许多其他解决方案,但找不到答案.我错过了什么?

I tried many other solutions, but cannot find the answer. What am I missing?

推荐答案

考虑使用 annotate() 将任何文本放置在绘图上给定位置的任何位置.因子变量,如 x 轴上的清晰度因子,每个级别都有一个数字,因此您可以使用该数字来定位文本.我假设日期变量具有相同的用法.:

Consider using annotate() to place whatever text where you want at a given location on the plot. Factor variables, as in the clarity factor on the x-axis, have a number for each level, so you can use that number to locate the text. I assume date variables have the same usage.:

ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar() +
  annotate("text", x=8, y=13000, label= "boat") + 
  annotate("text", x = 4, y=13000, label = "ship")

评论后编辑

为了效率,可以结合注解,比如这样:

For efficiency, you can combine the annotations, such as this:

ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar() +
  annotate("text", x = c(2,4,6,8), y=13000, label = c("two", "ship", "six", "boat"))

这篇关于将文本添加到 ggplot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆