【发布时间】:2015-04-08 17:55:50
【问题描述】:
EDIT* 解决方案附在这个问题的底部
我有一个带有注释的图表,可以将客户端更改为客户端。我需要文本以最大值右对齐,以便任何客户端名称长度都不会覆盖图形的其他区域。这是代码和产品。只希望文本始终在箭头旁边结束,并向左增长。
x <- c(1,1,1,1,1,1,2,2,2,2,2,2)
y <- c(0,0,0,0,0,0,0,0.33,0.17,0.16,0.14,0.2)
z<-data.frame(cbind(x,y))
client.name = "x"
client.year = 2015
ggplot<-
ggplot(z,aes(x = x,y = y,fill = y))+
geom_bar(stat = "identity",
fill = c("white","white","white","white","white","white",
"white","#c00000","#ed7d31","#ffc000","#92d050","#00b050"),width = .3)+
theme(legend.position = "none") +
theme(axis.ticks = element_blank()) +
theme(panel.grid = element_blank()) +
theme(axis.title = element_blank()) +
theme(axis.text = element_blank()) +
# theme(panel.background = element_blank()) +
theme(plot.margin = unit(c(0, 0, 0, 0), "cm"))+
geom_segment(aes(x = 1.77, y = .9, xend = 2.16, yend = .9),size=1.3,
arrow = arrow(angle = 20, length = unit(0.25, "inches"), ends = "first", type = "open"),linetype="solid")+
annotate("text", x = 2, y = c(0.167,0.415,0.58,0.73,0.9),
label = c("Disparaging","Unhappy","Ambivalent","Happy","Delighted"),
colour="white", fontface="bold", size=10) +
annotate("text", x = 1, y =.9, label = paste(client.name,client.year,paste0(.9, "%")),
fontface = "bold", hjust=0, size=10)
ggplot
这是带有长客户端名称的结果,手动调整到箭头旁边
这是具有最小可能客户端名称“x”的结果。
我可以通过使用每个名称的值将文本放到我想要的位置,但需要自动调整到最右边的箭头,以获取任何给定的名称(加分,我什至可以换行吗很长的名字!?不知道怎么做)。
有什么想法吗?
解决方案: 正如@baptiste 所指出的, hjust 是这里的关键选项。我知道是这种情况,但不知道 hjust 超出 0:1 的值会根据字符串长度改变锚点的位置。您可以看到我使用 -1 来获得正确的定位,而我应该操作 X。我通过将 hjust 设置为 1(右对齐)并将 X 调整到所需位置来解决我的问题。
感谢收看。
【问题讨论】:
-
请确保您的代码运行,现在有很多问题
标签: r ggplot2 annotations justify