如何让这个 ggplot2 geom_bar 图中的条形图使用 Rcolorbrewer 调色板?
Posted
技术标签:
【中文标题】如何让这个 ggplot2 geom_bar 图中的条形图使用 Rcolorbrewer 调色板?【英文标题】:How do I get the bars in this ggplot2 geom_bar graph to use Rcolorbrewer palette? 【发布时间】:2021-09-12 01:06:20 【问题描述】:我一直试图让我的图表条显示为 Rcolorbrewer“Set1”调色板,但我尝试的所有操作都会创建一个带有灰色条的图表。这是我尝试过的代码:
total_enrollment_by_year_plot <- ggplot(data = total_enrollment_by_year) +
geom_bar(mapping = aes(x = Year, y = Total_Enrollments), stat = "identity") +
labs(
title = "Total Patient Enrollment by Year, 2018-2020",
x = "Year", # x-axis label
y = "Patients Enrolled") + # y-axis label
scale_color_brewer(palette = "Set1")
我也绝望了,试图创建自己的图例来为每个条形添加颜色,但它也不起作用:
total_enrollment_by_year_plot <- ggplot(data = total_enrollment_by_year) +
geom_bar(mapping = aes(x = Year, y = Total_Enrollments), stat = "identity") +
labs(
title = "Total Patient Enrollment by Year, 2018-2020",
x = "Year", # x-axis label
y = "Patients Enrolled") + # y-axis label
scale_fill_manual("Legend", values = c("2018" = "Green", "2019" = "Blue", "2020"
= "Orange", "All Years" = "Red"))
我做错了什么?
【问题讨论】:
【参考方案1】:您需要在 aes 中添加填充,并且应该使用 scale_fill_brewer 而不是 scale_color_brewer。
total_enrollment_by_year_plot <- ggplot(data = total_enrollment_by_year) +
geom_bar(mapping = aes(x = Year, y = Total_Enrollments, fill = Year), stat = "identity") +
labs(
title = "Total Patient Enrollment by Year, 2018-2020",
x = "Year", # x-axis label
y = "Patients Enrolled") + # y-axis label
scale_fill_brewer(palette = "Set1")
【讨论】:
以上是关于如何让这个 ggplot2 geom_bar 图中的条形图使用 Rcolorbrewer 调色板?的主要内容,如果未能解决你的问题,请参考以下文章
在堆积条形图中反转 geom_text() (ggplot2)