如何从不同来源启动ggplot2 geom_bar [英] How to start ggplot2 geom_bar from different origin

查看:71
本文介绍了如何从不同来源启动ggplot2 geom_bar的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在y = 0以外的其他地方开始创建条形图.对于我来说,我想在y = 1处开始绘制条形图.

I'd like to start a bar chart at somewhere other than the y = 0. In my case, I want to start the bar chart at y = 1.

作为一个例子,假设我用ggplot2构建了一个身份geom_bar()图表.

As an example, let's say that I build a identity geom_bar() chart with ggplot2.

df <- data.frame(values = c(1, 2, 0),
                 labels = c("A", "B", "C"))

library(ggplot2)
ggplot(df, aes(x = labels, y = values, fill = labels, colour = labels)) + 
  geom_bar(stat="identity")

现在,我不问如何设置比例尺或轴限制.我希望代表小于1的值的条从y = 1向下流动.

Now, I'm not asking how to set scale or axis limits. I want bars representing values less than 1 to flow down from y = 1.

它看起来应该像这样...但是y轴不同:

It needs to look like this...but with a different y axis:

有什么建议吗?

推荐答案

您可以手动更改标签,如其他答案所示.但是,我认为从概念上讲,更好的解决方案是定义一个转换对象,该对象按要求转换y轴比例.使用这种方法,您实际上只是在修改条形图的相对基线,并且仍然可以像往常一样设置中断和限制.

You could just change the labels manually, as shown in the other answer. However, I think conceptually the better solution is to define a transformation object that transforms the y axis scale as requested. With that approach, you're literally just modifying the relative baseline for the bar plots, and you can still set breaks and limits as you normally would.

df <- data.frame(values = c(1,2,0), labels = c("A", "B", "C"))

t_shift <- scales::trans_new("shift",
                             transform = function(x) {x-1},
                             inverse = function(x) {x+1})

ggplot(df, aes(x = labels, y = values, fill = labels, colour = labels)) + 
  geom_bar(stat="identity") +
  scale_y_continuous(trans = t_shift)

设置中断和限制:

ggplot(df, aes(x = labels, y = values, fill = labels, colour = labels)) + 
  geom_bar(stat="identity") +
  scale_y_continuous(trans = t_shift,
                     limits = c(-0.5, 2.5),
                     breaks = c(0, 1, 2))

这篇关于如何从不同来源启动ggplot2 geom_bar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆