带有一个连续变量和两个分组变量的条形图

时间:2019-10-21 03:04:03

标签: r ggplot2

我将两个变量(湿度和温度)设置为因子,将连续(增长)设置为y变量。 我一直在输入代码以显示带有错误条形图的条形图,但是代码不断返回为

Error: Continuous value supplied to discrete scale

帮助?

sum1 <- summarySE(hw5data, measurevar = "growth", groupvars = c("temp", "humidity"), na.rm = TRUE)
sum1
temp humidity  N    growth      sd          se          ci
  15    25    10    45.69654    4.072518    1.2878433   2.913304
  20    25    10    23.67354    5.755927    1.8201841   4.117542
  25    25    10    34.77897    5.200555    1.6445600   3.720253
  15    50    10    44.26177    6.144309    1.9430012   4.395374
  20    50    10    26.07061    3.688428    1.1663833   2.638542
  25    50    10    34.49862    2.730160    0.8633525   1.95303


library(ggplot2)   
t <- ggplot(sum1, aes(x = temp, y = growth, fill = humidity)) + 
    geom_bar(stat = "identity", position = "dodge") +
    geom_errorbar(aes(ymin = growth - se, ymax = growth + se), width = .2,
                  position = position_dodge(.9)) + 
    coord_cartesian(ylim = c(0, 100))
t + 
    scale_fill_brewer(palette = "Reds") + 
    theme_classic()

1 个答案:

答案 0 :(得分:0)

为确保您的temphumidity变量是因素,

sum1$humidity = as.factor(sum1$humidity)
sum1$temp = as.factor(sum1$temp)

然后它应该工作:

ggplot(sum1, aes(x = temp, y = growth, fill = humidity)) + 
  geom_bar(stat = "identity", position = "dodge") +
  geom_errorbar(aes(ymin = growth - se, ymax = growth + se), width = .2,
                position = position_dodge(.9)) + 
  coord_cartesian(ylim = c(0, 100))+ 
  scale_fill_brewer(palette = "Reds") + 
  theme_classic()

enter image description here

使用的数据:

sum1 = as.data.frame(cbind(temp = c(15,20,25,15,20,25),
                           humidity = c(25,25,25,50,50,50),
                           growth = c(45.69654,23.67354,34.77897,44.26177,26.07061,34.49862),
                           se = c(1.2878433 ,1.8201841,1.6445600 ,1.9430012,1.1663833 ,0.8633525)))