R语言 如何使用ggplot对条形图和图例进行排序?

0h4hbjxa  于 2023-06-03  发布在  其他
关注(0)|答案(1)|浏览(258)

我如何获得按其中一个组(例如:老师)?以及如何更改标签,使顶部栏也是图例中的顶部标签?我尝试在创建数据集之前通过正确排序类别来更改它,但由于某种原因我没有更改条形图-

`df <- data.frame(Category = c("A","B", "C", "D", "E", "F"), 
                 Student = c(4.4,3.35,5.96,2.07,4.56,3.55), 
                 Teacher = c(3.21,4.39,5.3,1.8,2.8,3.14))

data.m <- melt(df, id.vars='Category')[![enter image description here](https://i.stack.imgur.com/KhsCP.png)](https://i.stack.imgur.com/KhsCP.png)

ggplot(data.m, aes(y = reorder(Category, value), x = value)) +
  geom_col(aes(fill = variable),
           position = position_dodge(width = 0.6), width = .6
  ) +
  geom_text(aes(label = value, group = variable),
            hjust = -0.2, size = 2.5,
            position = position_dodge(width = 0.6)
  ) +
  scale_x_continuous(expand = c(0, 0, .05, 0)) +
  scale_fill_brewer(palette = "Blues") +
  theme_classic() +
  labs(title = "Students and Teachers", x = "Category", y = "Means", fill = NULL)
`

我试着通过改变来重新排序;...aes(y = reorder(Category,-value),x = value))..但没有用

5lhxktic

5lhxktic1#

您可以只通过使用ifelse将学生值设置为零来重新排序教师值。要修复图例的顺序,您可以使用breaks=rev颠倒顺序:

library(ggplot2)

ggplot(
  data.m,
  aes(
    y = reorder(Category, ifelse(variable == "Teacher", value, 0), FUN = sum),
    x = value
  )
) +
  geom_col(aes(fill = variable),
    position = position_dodge(width = 0.6), width = .6
  ) +
  geom_text(aes(label = value, group = variable),
    hjust = -0.2, size = 2.5,
    position = position_dodge(width = 0.6)
  ) +
  scale_x_continuous(expand = c(0, 0, .05, 0)) +
  scale_fill_brewer(palette = "Blues", breaks = rev) +
  theme_classic() +
  labs(title = "Students and Teachers", x = "Category", y = "Means", fill = NULL)

相关问题