首页 > 解决方案 > 我想创建一个柱形图,其中每列是两种特定颜色之一

问题描述

我想制作一个柱形图,它采用变量“年”并为具有两个值之一的条形指定特定颜色。

我使用 ggplot 将实际情节放在一起,但是我不确定如何不仅根据“年”将其设置为颜色,而且将其设置为“第一年”的“红色”和上层阶级的“橙色”

structure(list(Hall = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 
8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, NA), .Label = c("Thurston", 
"MVC", "District House", "Mitchell", "Shenkman", "Potomac", "Guthridge", 
"Amdam", "South", "Lafayette", "JBKO", "Madison", "I House", 
"Dakota", "1959", "2109 F", "Fulbright", "Munson", "FSK"), class = "factor"), 
    Total = c(286, 262, 138, 118, 95, 85, 83, 76, 72, 69, 67, 
    67, 64, 60, 56, 52, 44, 43, 42, NA), years = structure(c(1L, 
    1L, 2L, 1L, 2L, 1L, 2L, 2L, 2L, 1L, 2L, 1L, 2L, 2L, 2L, 2L, 
    1L, 2L, 2L, 2L), .Label = c("First Year", "Upper-Class"), class = "factor")), class = "data.frame", row.names = c(NA, 
-20L))

library(ggplot2)

ggplot(fall5, aes(Hall, Total, width = .9)) + 
  geom_col(aes(fill = Total), position = "dodge2", color = years)+
  guides(fill=FALSE)  +
  theme(axis.text.x=element_text(angle=45, hjust = 1))

我希望看到与上面相同的图,但每一列都是基于“年”的两种颜色之一。此外,注明颜色差异的图例将很有用。

标签: rggplot2bar-chart

解决方案


library(ggplot2)
ggplot(fall5, aes(Hall, Total, width = .9)) + 
  geom_col(aes(fill = years), position = "dodge2")+
  scale_fill_manual(values = c("First Year" = "red",
                               "Upper-Class" = "orange")) +
  theme(axis.text.x=element_text(angle=45, hjust = 1))

推荐阅读