首页 > 解决方案 > 在 R 中更改绘图上的条形颜色

问题描述

library(ggplot2)

df <- data.frame(trt=c("TAVERN","Long Term Care","Grocery Store","Restaurant"),
                 outcome=c("a","b","c","d"))

ggplot(df,aes(trt, outcome)) + 
  geom_col() +
  geom_point(colour = 'red') +
  ggtitle("Failing rate in different facility types") + 
  labs(x="Facility type",y="Failing rate") + 
  theme(panel.background = element_blank()) +
  scale_color_manual(values = c("purple","green", "red", "orange"))

我试图手动更改 ggplot 中的颜色。

在此处输入图像描述

但我没有这样做。对此真的很困惑。

问题。如何设置ggplot()函数参数以更改条形颜色?

标签: rggplot2

解决方案


我假设您想更改条形的颜色。然后,您需要fill指定geom_col.

library(ggplot2)
df <- data.frame(trt=c("TAVERN","Long Term Care","Grocery Store","Restaurant"),
                 outcome=c("a","b","c","d"))
ggplot(df,aes(trt, outcome)) + 
  geom_col(fill=c("purple","green", "red", "orange")) + 
  geom_point(colour = 'red') + 
  ggtitle("Failing rate in different facility types") +
  labs(x="Facility type", y="Failing rate") +
  theme(panel.background = element_blank())

或者,您可以设置fill美学。请注意,这fill是针对内部的。 colour是为边界。

ggplot(df,aes(trt, outcome, fill=trt)) +
  geom_col() +
  geom_point(colour = 'red') + 
  ggtitle("Failing rate in different facility types") +
  labs(x="Facility type", y="Failing rate") +
  theme(panel.background = element_blank()) +
  scale_fill_manual(values = c("purple","green", "red", "orange"))

推荐阅读