【问题标题】:ggplot2 proportional bar graph: color only 1 of 17 levels per barggplot2 比例条形图:每个条形图仅着色 17 个级别中的 1 个
【发布时间】:2020-07-24 11:31:37
【问题描述】:

我对 R 和 SO 还很陌生,如果您对此提供任何帮助,我将不胜感激。

我有一个有 17 个级别的 factor 类数据。我正在使用library(ggplot2)geom_bar(position="fill") 创建一个比例条形图。代码和输出/绘图如下。

基本上,这很好,除了我希望能够创建另外 17 个这样的地块,并用一种​​方法突出显示其中一个级别(即一种颜色)保持不变,其余部分变灰作为区分一个级别与其他级别的一种方式。因为有 17 个关卡,而且颜色非常相似,所以现在很难区分某些关卡。

我希望这是有道理的——很高兴编辑并提供更多信息。我将不胜感激有关此问题的任何指示或帮助。非常感谢!


代码

# libraries
library(tidyverse) # for the plot
library(ggplot2) # for the plot
library(scales) # for the x-axis scaling
library(lubridate) # for the "POSIXct" and "POSIXt" class

#data classes
class(df.forum$p.date) # "POSIXct" "POSIXt"
class(df.forum$p.forum) # factor

# the plot
df.forum %>% 
  ggplot(aes(x = p.date, fill = factor(p.forum))) +
  geom_bar(position = "fill", stat = "count", show.legend = TRUE) + 
  theme(axis.text.x = element_text(angle = 90, hjust = 1,vjust = 0.2)) +
  scale_x_datetime(date_breaks = "1 month",labels = date_format("%b %Y"), limits = c(mdy_hms("10/1/13 20:00:00"),mdy_hms("5/1/14 20:00:00")))

情节

编辑/可重现示例

我还尝试建立一个可重现的示例,似乎这里可能存在问题:

    # data
d <- as.POSIXct(
  c("2020-01-01", "2020-01-01","2020-01-01", 
    "2020-01-02", "2020-01-02", "2020-01-02", 
    "2020-01-03", "2020-01-03", "2020-01-03"))

t <- as.factor(
  c("ATopic", "BTopic", "CTopic",
    "CTopic", "BTopic", "BTopic",
    "CTopic", "ATopic", "BTopic"))

df <- data.frame(d, t)

# the plot
df %>% 
  ggplot(aes(x = d, fill = factor(t))) +
  geom_bar(position = "fill", stat = "count") 

##E rror line: position_stack requires non-overlapping x intervals

这会产生以下带有错误“位置堆栈需要非重叠 x 间隔”的图:


编辑:按照建议应用 gghilight 并且成功了!这是我通过facet_wrap()gghighlight() 为人们提供的解决方案。

我也试过下面的代码:

library(gghighlight)
df %>% 
  ggplot(aes(x = factor(d), fill = factor(t))) +
  geom_bar(position = "stack", stat = "count") +
  facet_wrap(~t) +
  gghighlight()

这是输出:

【问题讨论】:

    标签: r ggplot2 colors geom-bar


    【解决方案1】:

    我认为使用gghighlight(结合facet_wrap)将满足您的需求。

    这里是一个使用iris 数据集的示例,以在每个物种的 Sepal.Length 函数中绘制 Sepal.Width。这里我使用facet_wrap 来分隔每个物种,gghighlight 是为了一次只显示一个物种的颜色

    library(ggplot2)
    library(gghighlight)
    
    ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species))+
      geom_point()+
      facet_wrap(~Species)+
      gghighlight()
    

    它回答了你的问题吗?

    如果没有,请考虑提供您的数据集的可重现示例 (How to make a great R reproducible example)

    【讨论】:

    • 当然。这正是我想要的。非常感谢@dc37!接受的答案和 +1。
    • 我在p.forum 上尝试了这个,它有 17 个级别。当我这样做时,我会失去其他层次的背景。这对 geom_bar 有什么不同吗?在此期间,我将尝试提供一个可重现的示例。
    • 添加到帖子的示例。在你的帮助下我得到了它!再次感谢 gghighlight 包的建议——不知道那个。 @dc37
    • 很高兴我的回答可以帮助您找出解决问题的方法;)
    猜你喜欢
    • 1970-01-01
    • 2019-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-06
    • 1970-01-01
    相关资源
    最近更新 更多