繁体   English   中英

ggplot boxplot:position_dodge不起作用

[英]ggplot boxplot: position_dodge does not work

我用ggplot做了一个相对简单的boxplot

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初学者。

有任何想法吗?

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

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))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM