使用scale_fill_brewer在ggplot上更改颜色的问题

时间:2019-01-01 23:05:58

标签: r ggplot2

enter image description here

我有一个要绘制的数据框,其中一列是类别,另一列是计数。

我使用了scale_fill_brewer,但是它没有改变任何颜色。颜色也关闭了-条形均为霓虹色。

我该如何解决?

数据框:

> dput(broad_cat)
structure(list(numbs = c(629, 526, 246, 86), labs = structure(c(4L, 
2L, 3L, 1L), .Label = c("Propaganda", "Public Service", "Public Welfare", 
"Social Welfare"), class = "factor")), .Names = c("numbs", "labs"
), row.names = c(NA, -4L), class = "data.frame")

地块代码:

p <- ggplot(broad_cat, 
            aes(reorder(broad_cat$labs, -(broad_cat$numbs), sum), 
                broad_cat$numbs))
p +
  geom_bar(stat = "identity", fill = broad_cat$numbs) + 
  labs(x = "Categories", y = "Counts") +
  ggtitle("Title[![enter image description here][1]][1]") + 
  theme(axis.title.x = element_text(size = 9),
        axis.title.y = element_text(size = 9),
        plot.title = element_text(size = 10, hjust = 0.5)) +
  scale_fill_brewer(palette = "Blues")

已修复:

我在fill中包括了aes(),但是图形仍然是黑白的。

aes(reorder(broad_cat$labs, -(broad_cat$numbs), sum), 
    broad_cat$numbs), fill = broad_cat$numbs)

1 个答案:

答案 0 :(得分:2)

由于numbs是数字,没有重复的值,因此我了解到您将fill用它只是为了获得一些漂亮的颜色。否则,如错误所示,由于numbs是连续的并且您的填充比例是离散的,因此它不起作用。也许以下是您想要的:

p <- ggplot(broad_cat, aes(reorder(labs, -numbs, sum), numbs))
p + geom_bar(stat = "identity", aes(fill = as.factor(numbs)), show.legend = FALSE) + 
  labs(x = "Categories", y = "Counts") + 
  ggtitle("Title[![enter image description here][1]][1]") + 
  theme(axis.title.x = element_text(size = 9),
        axis.title.y = element_text(size = 9),
        plot.title = element_text(size = 10, hjust = 0.5)) + 
  scale_fill_brewer(palette = "Blues")

enter image description here

主要用途是在fill内使用aes,将numbs转换为使用离散比例的因子,并且我也删除了所有broad_cat$...会导致问题,变量应直接用名称来引用。