【问题标题】:Readjusting the horizontal axis in ggplot重新调整ggplot中的水平轴
【发布时间】:2019-07-16 20:24:10
【问题描述】:

我有一个简单的数据集,包含从 0 到 1 的值。当我绘制它时,水平轴自然为零。我希望这个参考值为 0.5,低于 0.5 的条形图与高于该阈值的条形图反转和着色。

my.df <- data.frame(group=state.name[1:20],col1 = runif(20))

p <- ggplot(my.df, aes(x=group,y=col1)) +
 geom_bar(stat="identity")+ylim(0,0.5)

我正在考虑将数据分成两部分,一个大于 0.5,另一个大于 0.5,然后将这两个子集结合在同一个 ggplot 中。还有其他更清晰的方法吗?谢谢!

【问题讨论】:

标签: r ggplot2 geom-bar


【解决方案1】:

要以@jas_hughes 的回答为基础,您可以从 col1 变量中减去 0.5,然后重命名 y 轴上的标签。

df <- data.frame(group=state.name[1:20],value=runif(20))

df %>% ggplot(aes(reorder(group,value),value-0.5)) + geom_bar(stat='identity') +
  scale_y_discrete(name='Value',
                   labels=c('0','0.5','1'),
                   limits=c(-0.5,0,0.5),
                   expand = c(-0.55, 0.55)) + 
  xlab('State') + 
  theme(axis.text.x = element_text(angle=45,hjust=1))

【讨论】:

    【解决方案2】:

    您尝试传达的 y 变量距离 0.5,因此您需要更改 col1 中的值以反映这一点。

    library(dplyr)
    library(ggplot)
    my.df %>% 
      mutate(col2 = col1-0.5) %>% 
      ggplot() +
      aes(x = group, y = col2, fill = col2 >=0) + 
      geom_bar(stat = 'identity') + 
      theme(legend.position = 'none', 
            axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1)) + 
      ylab('Col1 above 0.5 (AU)')
    

    注意,您也可以使用 aes(fill = col1 &gt;= 0.5) 选项对条形进行颜色编码,而无需移动轴(如果 col1 包含百分比,我建议这样做)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-05
      • 1970-01-01
      • 2014-09-29
      • 1970-01-01
      • 2020-03-11
      • 1970-01-01
      相关资源
      最近更新 更多