条形图-条形图跳到y轴

时间:2020-05-07 18:13:19

标签: r ggplot2 bar-chart zero

我正在绘制一个条形图,其中的代码运行良好,直到某些数据的值为0。

barwidth = 0.35

df1:
norms_number   R2.c 
1             0.011     
2             0         
3             0.015         
4             0.011         
5             0         
6             0.012

df2:
norms_number  R2.c
1           0.001           
2           0           
3           0.012           
4           0.006           
5           0           
6           0.004

test <- ggplot()+
geom_bar(data=df1, aes(x=norms_number, y=R2.c),stat="identity", position="dodge", width = barwidth)+
  geom_bar(data=df2, aes(x=norms_number+barwidth+0.03, y=R2.c), 
stat="identity",  position="dodge",width = barwidth)

我的结果是:

enter image description here

我得到一个警告,即位置堆栈需要不重叠的x间隔(但它们不重叠吗?)

我调查了一下,并将DV更改为因子(从数字),这有一半是有用的,因为现在的图形如下:

enter image description here

为什么y轴上的条形?我还能如何解决这个值为0的怪异错误?

2 个答案:

答案 0 :(得分:0)

首先,您打算绘制一个条形图,其中高度用而不是例数表示。 See here for more details,但您应该使用geom_col而不是geom_bar

话虽如此,您得到的错误和结果是因为看来x=norms_number+barwidth+0.03试图指定第二组数据(df2)相对于df1的精确位置第一组数据(ggplot)。

为了使x=闪避,它必须了解将什么用作闪避的基础,然后它将分离(或“闪避”)每个包含相同aes(美学的观察值基于作为基础的特定人群。在正常情况下,您可以在fill=中指定类似ggplot之类的内容,并且fill=足够聪明,可以知道您设置为position='dodge'的任何内容也将成为{{ 1}}起作用。在这种情况下(或者如果您想覆盖它),则需要指定一种group=美观性,用于躲避。

最终,这意味着您需要组合数据集并为ggplot提供一种确定如何躲避的方法。这是有道理的,因为您的两个数据框都打算放置在同一图中,并且具有相同的xy美观性。如果将它们保留为单独的数据帧,则可以在同一图中对它们进行过度绘制,但是没有ggplot使用position='dodge'的好方法,因为它需要查看{{1 }}进行呼叫,以了解使用什么作为躲闪的基础。

话虽如此,以下是我的建议:

geom_col

然后,您只需使用一次致电# combine datasets, but first make a marker called "origin" # this will be used as a basis for the dodge and fill aesthetics df1$origin <- 'df1' df2$origin <- 'df2' df <- rbind(df1, df2) # need to change norms_number to a factor to allow for discrete axis df$norms_number <- as.factor(df$norms_number) 即可获得绘图。在第一种情况下,我将仅使用geom_col美学来向您展示group=如何将其用于闪避机制:

ggplot

enter image description here

如前所述,您还可以提供ggplot(df, aes(x=norms_number, y=R2.c)) + geom_col(position='dodge', width=0.35, aes(group=origin), color='black') 的美感,fill=会知道将其用作躲避的机制:

ggplot

enter image description here

答案 1 :(得分:0)

不太确定是否要在条形图上绘制更复杂的图形,如条形图等。无论如何,一种方法是使用geom_rect()(如果要在另一条形图上使用):

ggplot()+
geom_rect(data=df1, 
aes(xmin=norms_number-barwidth,xmax=norms_number,
ymin=0,ymax=R2.c))+
geom_rect(data=df2, 
aes(xmin=norms_number,xmax=norms_number+barwidth,
ymin=0,ymax=R2.c))+
scale_x_continuous(breaks=1:6)

enter image description here