r - 条形图 ggplot : conflict between values on bar and x axis label

标签 r ggplot2

我正在努力使用我的代码来使用 ggplot2 创建条形图,我尝试在其中添加 y条形顶部的值,但不移动 x 的标签轴。 geom_text在栏上添加值效果很好,但是我无法调整 x旋转 45° 时,轴标签正确(即标签的最后一个字母粘贴在轴上)。

我的数据

 dput(graph)
structure(list(x = structure(1:9, .Label = c("AAAAAAAAAAAAA", 
"BBBBBBBB", "CCCCCCCCCCCCCCCC", "DDDDD", "EEEEEEEE", "FFFFFFF", 
"GGGGGGGGGGGGGGG", "HHHHHHHHHHHHHH", "IIIII"), class = "factor"), 
    y = c(1L, 5L, 10L, 1000L, 20L, 15L, 45L, 30L, 35L)), .Names = c("x", 
"y"), class = "data.frame", row.names = c(NA, -9L))

我的代码:

graph <- read.table("input.txt",header=T,sep=";")
output <- ggplot(graph,aes(x=x,y=y))+
    geom_bar(stat="identity")+
    geom_text(aes(label=y,y=(y+25)))+
    scale_x_discrete()+
    scale_y_continuous(limits=c(0,max(50 + graph$y)))+
    theme(axis.text.x=element_text(angle=45,vjust=0))
print(output)

我无法发布输出图像,但除了 x 的刻度线之外,绘图看起来不错。轴适合 x 的中间标签而不是标签的最后一个字母。

最佳答案

您应该将 hjust=1 添加到 axis.text.x= 并将 vjust=0 更改为 vjust=1。要更改条形的外观,您可以尝试使用 y 值的转换,例如使用 scale_y_sqrt() 进行平方根。仅应调整 geom_text() 的位置。

output <- ggplot(graph,aes(x=x,y=y))+
  geom_bar(stat="identity")+
  geom_text(aes(label=y,y=(y+c(10,10,10,50,10,10,10,10,10))))+
  scale_y_sqrt(limits=c(0,max(50 + graph$y)),breaks=c(10,100,250,500,1000))+
  theme(axis.text.x=element_text(angle=45,vjust=1,hjust=1))
output

enter image description here

关于r - 条形图 ggplot : conflict between values on bar and x axis label,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14908492/

相关文章:

r - 使用 R 计算边际税率

r - 使用ggplot2重复悬停信息

r - geom_polygon + map projection = 莫名其妙的切成两个形状?

r - excel函数“搜索R中的决策函数,但针对两个或多个未知数

R 删除包含特定值的行

r - 如何将 difftime 转换为字符串 "X hours Y minutes Z seconds"

r - 等号更改生存对象自动绘图中图例标签的呈现

r - ggplot2 绘制横向填充页面 (pdf)

r - 如何更改 ggforest(或 coxph 回归图)中的绘图大小?

r - 使用 ggplot 绘制 parking 场占用的 parking 位