首页 > 解决方案 > 在没有图例的情况下将比例渐变颜色应用于 R 中的条形图

问题描述

我正在尝试将渐变颜色应用于这两个共享相同值的条形图:

左侧的条形图显示了 9 个英国地区在 1 年内的平均失业率,而右侧的条形图显示了同一年的失业率变化。

在此处输入图像描述

所需输出:颜色渐变低 = 黄色,高 = 红色,以突出显示具有最高/最低失业率平均值和波动性的区域(= 条形图)。#

这是我正在使用的代码:

  unemployment_data %>% 
  tidyr::pivot_longer(-Region) %>% 
  ggplot(aes(x=Region, y=value)) +
  geom_bar(stat='identity') +
  scale_y_continuous(name = "Unemployment Rate (%)") +
  theme(axis.text.x=element_text(angle =- 90, vjust = 0.5)) +
  facet_wrap(~name)

这是结构:

        structure(list(
Region = c("SE", "SW", "EASTof", "LDN", "E_Mid", 
  "W_Mid", "Yorks", "NW", "NE"), 
Unemployment.rate.average = c(3.21824018447441, 
  3.05119829228833, 3.44297331188711, 4.7077689256265, 4.23448912295878, 
  4.67588411516106, 4.45220611226308, 4.06868093338517, 5.69591652090698
  ), 
Unemployment.rate.change = c(0.736310637450949, 1.46412090540429, 2.12686434777655, 
  1.45717316978403, 0.637927880295394, 0.332156994549906, -0.0793646423962819, 
  1.1068637830205, 1.51263456155816)), 
class = "data.frame", row.names = c(NA, -9L))

我在网上找到的所有示例都使用图例作为渐变,但在我的情况下,我有两个条形图,其 Y 值取自同一数据框的两个不同列 - “平均”列和“更改”列,以及我的情节中真的不需要传奇。

在此先感谢您的帮助!

标签: rggplot2colorsbar-chart

解决方案


像这样的东西:

unemployment_data %>% 
  tidyr::pivot_longer(-Region) %>% 
  ggplot(aes(x=Region, y=value, fill=value)) +
  geom_bar(stat='identity', show.legend=FALSE) +
  scale_fill_gradient(low="yellow", high = "red") + 
  scale_y_continuous(name = "Unemployment Rate (%)") +
  theme(axis.text.x=element_text(angle =- 90, vjust = 0.5)) +
  facet_wrap(~name)

在此处输入图像描述


编辑:每个面板的不同坡道

为了回应关于在每个面板中使坡道不同的评论,可能有一种更优雅的方式来做到这一点,但你可以用两个图来做到这一点:

library(dplyr)
library(ggplot2)
library(gridExtra)

p1 <- unemployment_data %>% 
  mutate(name1 = "Unemployment Rate Average") %>% 
  ggplot(aes(x=Region, 
             y=Unemployment.rate.average, 
             fill=Unemployment.rate.average)) +
  geom_bar(stat='identity', show.legend=FALSE) +
  scale_fill_gradient(low="yellow", high = "red") + 
  labs(y = "Unemployment Rate (%)", x="") +
  theme(axis.text.x=element_text(angle =- 90, vjust = 0.5)) +
  facet_wrap(~name1) + 
  coord_cartesian(ylim=c(0,6), expand=0)

p2 <- unemployment_data %>% 
  mutate(name2 = "Unemployment Rate Change") %>% 
  ggplot(aes(x=Region, 
             y=Unemployment.rate.change, 
             fill=Unemployment.rate.change)) +
  geom_bar(stat='identity', show.legend=FALSE) +
  scale_fill_gradient(low="yellow", high = "red") + 
  labs(x="", y="") + 
  theme(axis.text.x=element_text(angle =- 90, vjust = 0.5), 
        axis.title.y=element_blank(),
        axis.text.y=element_blank(),
        axis.ticks.y=element_blank()) +
  facet_wrap(~name2) + 
  coord_cartesian(ylim=c(0,6), expand=0)

grid.arrange(p1, p2, nrow=1, bottom="Region")

在此处输入图像描述


推荐阅读