【问题标题】:ggplot: how to repeal the alphabetical order [duplicate]ggplot:如何废除字母顺序[重复]
【发布时间】:2018-12-12 12:46:09
【问题描述】:

我在 R 中使用 ggplot2

这是我的数据集的样子:

| Value | Big_condition | little_condition |
|-------|---------------|------------------|
| 10    | a             | A                |
| 12    | a             | B                |
| 11    | a             | A                |
| 6     | b             | B                |
| 10    | b             | B                |
| 8     | b             | A                |
| 9     | c             | B                |

这是我的代码:

#Thanks Jordo82 for this part    
dataset <- data.frame(Value = c(10,12,11,6,10,8,9),
                      Big_condition = letters[c(1,1,1,2,2,2,3)],
                      little_condition = LETTERS[c(1,2,1,2,2,1,2)])

# My ggplot code
p <- ggplot(data=dataset, aes(x=dataset$little_condition , y=dataset$value)) + 
  geom_boxplot() + 
  ylim(0, 20) + 
  theme_classic() + 
  geom_dotplot(binaxis='y', stackdir='center', dotsize=0.2) + 
  facet_grid(cols=vars(dataset$big_condition))

这是我得到的:

我想颠倒“小”条件(B,A)的顺序,选择“大”条件的顺序(例如c,a,b,e,f,d) .

如何做到这一点?

谢谢!

(这与它无关,但我也在寻找一种方法来仅显示我的点的平均值,而不显示箱线图的其余部分)。

【问题讨论】:

  • 使用所需的顺序重构变量。

标签: r ggplot2 visualization


【解决方案1】:

要更改图中的顺序,您必须重新排序因子。至于你的第二个问题,只绘制每个点的平均值,summarise 先绘制数据,然后使用geom_point 绘制。

library(tidyverse)

dataset <- data.frame(Value = c(10,12,11,6,10,8,9),
                      Big_condition = letters[c(1,1,1,2,2,2,3)],
                      little_condition = LETTERS[c(1,2,1,2,2,1,2)])

#calculate the average value for each combination of conditions
dataset_mean <- dataset %>% 
  group_by(Big_condition, little_condition) %>% 
  summarise(MeanValue = mean(Value))

dataset %>%
  #reorder the factors to control the order in which they are plotted
  mutate(Big_condition = factor(Big_condition, levels = c("c", "a", "b")),
         little_condition = factor(little_condition, levels = c("B", "A"))) %>% 
  #create the plot
  ggplot(aes(x=little_condition , y=Value)) + 
  #plot a point for all values
  geom_point() + 
  #plot a line for the mean of values
  geom_point(data = dataset_mean, aes(x=little_condition , y=MeanValue), 
            color = "red", size = 6, shape = 95) +
  ylim(0, 20) + 
  theme_classic() + 
  facet_grid(.~Big_condition)

【讨论】:

  • 您好,非常感谢!我正在尝试您的解决方案(使用您的所有代码),但这是我第一次看到 %>% 并且 R studio 似乎不喜欢它。 R告诉我“数据集中错误%>% mutate(Big_condition = factor(Big_condition, levels = c("c", :不可能找到函数"%>%" (对于第二个问题,我实际上想要我所有的个人点加上一条线作为平均值。)
  • 编辑了我的答案以绘制所有点和平均值。确保您安装并加载了tidyverse 包,以便能够使用管道运算符%&gt;%。这是一个非常有用的工具,在这里了解更多信息:r4ds.had.co.nz/pipes.html
猜你喜欢
  • 2021-08-19
  • 2022-11-17
  • 2019-12-07
  • 1970-01-01
  • 2014-12-21
  • 1970-01-01
  • 1970-01-01
  • 2019-12-16
  • 1970-01-01
相关资源
最近更新 更多