gpt4 book ai didi

r - R : barchart with log scale label misplacement 中的 ggplot

转载 作者:行者123 更新时间:2023-12-01 08:05:42 25 4
gpt4 key购买 nike

所以我要制作一个条形图,并且由于数据范围的原因,y 轴的对数图是有保证的。所以问题是我的值为 0.5,在 log10 中为 -0.3。由于条形变为负数,用于放置标签的条形的“顶部”实际上是“底部”,因此我的文本标签“刚好在”底部,这意味着在条形的中间。我想我可能不是第一个遇到这个问题的人,但搜索相关修复程序并没有帮助。最值得注意的是,我尝试使用闪避,但这并没有改变栏的“顶部”实际上是“底部”。

所以两个问题:

  1. 我可以解决这个标签问题吗?
  2. 这很丑陋:我可以将 x 轴向上移动到 y=1 以在不移动 x 轴标签的情况下为负值提供更多上下文吗?

.

alpha=c('A','B','C','D')
value=c(0.5,10,40,1100)
table<-as.data.frame(alpha)
table<-cbind(table, value)
library(ggplot2)
graph <- ggplot(table, aes(x=alpha)) +
geom_bar(stat="identity",aes(y=value),width=0.5) +
geom_text(aes(y=value,label=value),vjust=-0.5) +
scale_y_continuous(trans="log10",limits=c(0.5,1400))
graph + theme_classic()

graph with labels incorrect

最佳答案

修改数据标签的y坐标的小技巧(使用ifelse()y的值设置为 1 如果值小于一)。至于轴,只需隐藏 X 轴(将其设置为 element_blank())并绘制一条新的水平线:

graph <- ggplot(table, aes(x=alpha)) + 
geom_bar(stat="identity",aes(y=value),width=0.5) +
# Modify the placing of the label using 'ifelse()':
geom_text(aes(y=ifelse(value < 1, 1, value),label=value),vjust=-0.5) +
scale_y_continuous(trans="log10",limits=c(0.5,1400)) +
theme_classic() +
# Hide the X axis:
theme(axis.line.x = element_blank()) +
# Draw the new axis
geom_hline()
print(graph)

输出:

Output for code above

关于r - R : barchart with log scale label misplacement 中的 ggplot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31994951/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com