ggplot:如何废除字母顺序

时间:2018-12-12 12:46:09

标签: r ggplot2 visualization

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

这就是我得到的:

image from https://imgur.com/a/S3MGXst

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

该怎么做?

谢谢!

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

1 个答案:

答案 0 :(得分:2)

要更改图中的顺序,您必须重新排列因子。至于第二个问题,要只绘制每个点的平均值,请先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)

enter image description here