Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 将文本添加到绘图_R_Ggplot2_Label - Fatal编程技术网

R 将文本添加到绘图

R 将文本添加到绘图,r,ggplot2,label,R,Ggplot2,Label,(更新) 我有这样的绘图,但x轴日期缩放: g1 <- ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar() 然后我得到一个错误: 错误:美学长度必须为1,或与 数据问题:c(截止日期(“2014-10-05”)、截止日期(“2014-10-20”)) 我还尝试从数据框(oefen)中读取文本和标签,其中我使用了与原始绘图相同的名称 g1 + geom_text(data=oefen, aes(x=newdat, y=Number,

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

g1 <- ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar()
然后我得到一个错误:

错误:美学长度必须为1,或与 数据问题:c(截止日期(“2014-10-05”)、截止日期(“2014-10-20”))

我还尝试从数据框(
oefen
)中读取文本和标签,其中我使用了与原始绘图相同的名称

g1 + geom_text(data=oefen, aes(x=newdat, y=Number, label=oefen$labs, fill=1))
我得到了错误

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


我尝试了许多其他的解决办法,但找不到答案。我遗漏了什么?

考虑使用
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"))

没有可复制的示例,很难理解。不过,您好,谢谢您的回答。您的解决方案很接近,但我想要的只是那些字母(所以没有条形图),它们绘制在我原来的g1堆叠条形图上。我有这样一个条形图:ggplot(diamonds,aes(clearity,fill=cut))+geom_bar(),但xaxis是一个日期变量。我只想在两条横线上方画一个字母。更清晰吗?@Rosanne请使用diamonds数据集发布一个简单的可复制代码示例。@smci我给了它一个更新,是这样更清晰吗?非常感谢,这正是我想要的。我以前试过使用annotate,但那时候不起作用,可能是太糟糕了。我只是想知道,当我想添加6个标签时,是否有一种方法可以在一段脚本中组合所有标签,而不是使用注释6次?不管怎样,我现在就把它放下6次,因为它终于起作用了。非常感谢你!!我为一行中的多个注释添加了建议的技术。如果这回答了你的问题,请考虑接受。谢谢
ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar() +
  annotate("text", x = c(2,4,6,8), y=13000, label = c("two", "ship", "six", "boat"))