首页 > 解决方案 > ggplot boxplot:position_dodge 不起作用

问题描述

我用 ggplot 做了一个相对简单的箱线图

ggplot(l8tc.df_17_18,aes(x=landcover,y= tcw_17, group=landcover))+
geom_boxplot()+
geom_boxplot(aes(y= tcw_18),position_dodge(1))

用于了解所用数据的屏幕截图:

数据框截图

这是输出:

箱形图

我希望不同的箱线图彼此相邻,而不是在一条垂直线上。我查看了所有相关问题并尝试了几个选项,但是到目前为止我找不到解决方案。

不过,我仍然是 ggplot 初学者。

有任何想法吗?

标签: rggplot2boxplot

解决方案


在这种情况下,您应该使用不同的数据格式并将其融化。

require(reshape2) 
require(tidyverse) 

# format data
melted_data <- l8tc.df_17_18 %>%
    select(landcover, tcw_17, tcw_18) %>%  
    melt('landcover', variable.name = 'tcw')

# plot
ggplot(melted_data, aes(x = as.factor(landcover), y = value)) + geom_boxplot(aes(fill = tcw))

闪避应该是自动的,但如果你想进行实验,请使用geom_boxplot(aes(fill = tcw), position = position_dodge())
https://ggplot2.tidyverse.org/reference/position_dodge.html

您可以在一行中编写它而无需创建临时文件

l8tc.df_17_18 %>% 
    select(landcover, tcw_17, tcw_18) %>% 
    melt('landcover', variable.name = 'tcw') %>% 
    ggplot(aes(x = as.factor(landcover), y = value)) + geom_boxplot(aes(fill = tcw))

推荐阅读