修复 ggplot 中分面的顺序 [英] Fixing the order of facets in ggplot

查看:20
本文介绍了修复 ggplot 中分面的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

数据:

df <- data.frame(
    type   = c("T", "F", "P", "T", "F", "P", "T", "F", "P", "T", "F", "P"), 
    size   = c("50%", "50%", "50%", "100%", "100%", "100%", "150%", "150%", "150%", "200%", "200%", "200%"),
    amount = c(48.4, 48.1, 46.8, 25.9, 26, 24.9, 21.1, 21.4, 20.1, 20.8, 21.5, 16.5)
)

我需要使用 ggplot (x-axis -> type, y-axis -> amount, group by >尺寸).当我使用以下代码时,我没有按照数据中显示的顺序获取变量 typesize.请看图.我为此使用了以下代码.

I need to plot a bargraph of the above data using ggplot (x-axis -> type, y-axis -> amount, group by size). When I used the following code, I am not getting the variable type and as well as size in the order shown in the data. Please see the figure. I have used the following code for that.

 ggplot(df, aes(type, amount , fill=type, group=type, shape=type, facets=size)) + 
  geom_col(width=0.5, position = position_dodge(width=0.6)) + 
  facet_grid(.~size) + 
  theme_bw() + 
  scale_fill_manual(values = c("darkblue","steelblue1","steelblue4"), 
                    labels = c("T", "F", "P"))

.

为了解决订单问题,我对变量type"使用了因子方法;使用以下.也请看图.

For fixing the order issue, I have used a factor method for the variable "type" using the following. Please see the figure also.

temp$new = factor(temp$type, levels=c("T","F","P"), labels=c("T","F","P")) 

但是,现在我不知道如何修复变量 size 的顺序.它应该是 50%、100%.150% 和 200%.

However, now I don't know how to fix the order for the variable size. It should be 50%, 100%. 150%, and 200%.

推荐答案

通过以下方式使您的大小成为数据框的一个因素:

Make your size a factor in your dataframe by:

temp$size_f = factor(temp$size, levels=c('50%','100%','150%','200%'))

然后将facet_grid(.~size)改为facet_grid(.~size_f)

然后绘制:

图表现在的顺序正确.

这篇关于修复 ggplot 中分面的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆