r - 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 初学者。
有任何想法吗?
解决方案
在这种情况下,您应该使用不同的数据格式并将其融化。
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))
推荐阅读
- c# - 我使用 Visual Studio Community 进行学习是否合法?
- kubernetes - 错误:添加选择器后`选择器`与模板`标签`不匹配
- java - 建模一个复数,我在创建我的类时缺少一个 main 方法。有人可以指导我如何解决它吗?
- saml-2.0 - 我可以使用 ITfoxtec saml2 将 SAML 身份提供者添加到非核心网站吗?
- nginx - 客户端在 60 秒时从我的 flask/gunicorn/nginx-ingress 堆栈中收到 RemoteDisconnected 错误。为什么?超时设置...没有
- r - 如何将变量从 data.frame 循环到另一个到单个列中
- php - 转换 nvarchar 值时 Laravel 转换失败
- swift - 为什么 Swift 不会自动处理内存泄漏?
- javascript - 尝试制作一个当结果为负数时显示红色文本的计算器
- node.js - 重新启动使用 pm2-runtime 运行的 Node 应用程序会导致容器消失,但应用程序仍在运行