问题描述
我只想为 ggplot 中的一个条着色.这是我的数据框:
I want to color only one bar in ggplot. This is my data frame:
area <- c("Północ", "Południe", "Wschód", "Zachód")
sale <- c(16.5, 13.5, 14, 13)
df.sale <- data.frame(area, sale)
colnames(df.sale) <- c("Obszar sprzedaży", "Liczba sprzedanych produktów (w tys.)")
以及绘图代码:
plot.sale.bad <- ggplot(data=df.sale, aes(x=area, y=sale, fill=area)) +
geom_bar(stat="identity") +
scale_fill_manual(values=c("black", "red", "black", "black")) +
xlab(colnames(df.sale)[1]) +
ylab(colnames(df.sale)[2]) +
ggtitle("Porównanie sprzedaży")
我希望只有一个颜色条和另外 3 个具有默认颜色(深灰色,不是黑色,对我来说看起来很糟糕).如何仅更改条形图的颜色或如何获取条形图的默认颜色名称以将它们放置而不是黑色?
I would like to have only one bar colored and 3 others to have default color (darkgrey, not black, it looks bad for me). How can I change color of only on bar or how to get name of the default color of bars to put them instead of black?
推荐答案
选项 1:仅更改一个栏的颜色.按照 Henrick 的建议,您可以创建一个新变量,其中包含默认颜色的 NA 和非默认颜色的字符串/因子(第一个恰好是红色):
Option 1: Change color of only one bar. Following Henrick's suggestion, you can create a new variable with NAs for the default color and character strings/factors for non-default colors (the first one happens to be red):
area.color <- c(NA, "withcolor", NA, NA)
plot.sale.bad <- ggplot(data=df.sale, aes(x=area, y=sale, fill=area.color)) +
geom_bar(stat="identity") +
xlab(colnames(df.sale)[1]) +
ylab(colnames(df.sale)[2]) +
ggtitle("Porównanie sprzedaży")
plot.sale.bad
选项 2:找到您喜欢的默认深灰色名称.如果您简单地删除原始代码中的 scale_fill_manual
行(在这种情况下,您会得到四种不同的粉彩),这不是默认颜色,所以我假设您的意思是代码块产生的灰色在本段上方,对于那些 area.color==NA
的条形图.在这种情况下,您可能会查看 scale_fill_discrete
的源代码(或 args,无论如何):
Option 2: Find the name of the default dark gray color you like. This is not the default color if you simply remove the scale_fill_manual
line in your original code (in that case, you get four different pastels), so I assume you mean the grey color produced by the code chunk just above this paragraph, for those bars where area.color==NA
. In that case, you might look at the source code (or args, anyway) for scale_fill_discrete
:
> args(scale_fill_discrete)
# function (..., h = c(0, 360) + 15, c = 100, l = 65, h.start = 0,
# direction = 1, na.value = "grey50")
# NULL
na.value
的默认值是 "grey50"
.所以如果你想使用 scale_fill_manual
,你可以这样做:
The default for na.value
is "grey50"
. So if you wanted to use scale_fill_manual
, you could do it like so:
plot.sale.bad <- ggplot(data=df.sale, aes(x=area, y=sale, fill=area)) +
geom_bar(stat="identity") +
scale_fill_manual(values=c("grey50", "red", "grey50", "grey50")) +
xlab(colnames(df.sale)[1]) +
ylab(colnames(df.sale)[2]) +
ggtitle("Porównanie sprzedaży")
plot.sale.bad
这篇关于更改 ggplot 中只有一个条的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!