【问题标题】:Why I cannot add colours to my bar chart in Rstudio? [duplicate]为什么我不能在 Rstudio 中为我的条形图添加颜色? [复制]
【发布时间】:2021-01-06 19:58:06
【问题描述】:

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

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

【问题讨论】:

  • ggplot(data=episode_data, aes(x=season, fill = season))

标签: r ggplot2 colors bar-chart


【解决方案1】:

由于没有提供数据,我将向您解释使用演示数据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')

输出:

第二个选项是直接在geom_bar() 中启用fill 选项,并使用一些定义的颜色,如下所示:

#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')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-29
    • 2015-09-20
    • 2018-07-11
    • 2018-03-21
    • 1970-01-01
    • 2013-02-06
    • 2023-04-03
    相关资源
    最近更新 更多