首页 > 解决方案 > 为什么我不能在 Rstudio 中为我的条形图添加颜色?

问题描述

我使用了下面的代码,但它只显示没有颜色的图表

gbar <- ggplot(data=episode_data, aes(x=season))
gbar + 
   geom_bar() +
   scale_fill_brewer(type = "seq", palette = 1, direction = 1, aesthetics = "fill") 

在此处输入图像描述

标签: rggplot2colorsbar-chart

解决方案


由于没有提供数据,我将向您解释使用演示数据在绘图中添加颜色的两种方法iris。您可以设置美学元素fill以添加一些变量来填充您的条形图。使用该选项的代码输出将是下一个:

library(ggplot2)
library(tidyverse)
#Data
data("iris")
#Example 1 color by species
iris %>% pivot_longer(-Species) %>%
  ggplot(aes(x=name,y=value,fill=Species))+
  geom_bar(stat='identity')

输出:

在此处输入图像描述

第二个选项将直接fill在内部启用选项,geom_bar()其中包含一些定义的颜色,如下所示:

#Examples 2 only one color
iris %>% pivot_longer(-Species) %>%
  ggplot(aes(x=name,y=value))+
  geom_bar(stat='identity',fill='cyan3')

输出:

在此处输入图像描述

对于您添加的代码,请尝试此操作,下次请包含您的数据示例以重现您的问题:

#Option 1
ggplot(data=episode_data, aes(x=season))+
  geom_bar(stat='identity',fill='red')
#Option 2
ggplot(data=episode_data, aes(x=season,fill=factor(season)))+
  geom_bar(stat='identity')

推荐阅读