【发布时间】: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
编辑:按照建议应用 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()
【问题讨论】: