英文:
Changing color of only one stacked bar using ggplot
问题
我在R(markdown)中使用ggplot创建了一个堆叠条形图。我想要将“north”对应的堆叠条以灰度显示,而保持其他条的当前颜色。实际上,我正在处理一个更大的数据集,所以最好的解决方案应该能够找到x = "north"的位置,并仅将该条变成灰度。
Region <- c("north", "south", "east", "west", "north", "south", "east", "west")
q14 <- c("5", "5", "5", "5", "4", "4", "4", "4")
N <- c(4342, 5325, 654, 1231, 3453, 234, 345, 5634)
Percentage <- c(72, 71, 68, 67, 21, 20, 18, 17)
df <- data.frame(Region, q14, N, Percentage)
ggplot(df, aes(x=Region, y = Percentage, fill = q14, label = Percentage)) +
geom_bar(stat = "identity") +
scale_fill_manual(values = c("#bbd6ad", "gray", "#63ab41", "#63ab41"))
非常感谢帮助!我尝试过调整scale_fill_manual
,但没有取得好的结果,只导致所有条的颜色都改变。
英文:
I have a stacked bar chart made with ggplot in R (markdown). I want the stacked bar for "north" to be in a grayscale, and the other bars to stay in the color scale they currently are. I am in reality working with a lot larger data set, so the solution should preferably find where x = "north" and grayscale only that bar.
Region <- c("north", "south", "east", "west", "north", "south", "east", "west")
q14 <- c("5", "5", "5", "5", "4", "4", "4", "4")
N <- c(4342, 5325, 654, 1231, 3453, 234, 345, 5634)
Percentage <- c(72, 71, 68, 67, 21, 20, 18, 17)
df <- data.frame(Region, q14, N, Percentage)
ggplot(df, aes(x=Region, y = Percentage, fill = q14, label = Percentage)) +
geom_bar(stat = "identity") +
scale_fill_manual(values = c("#bbd6ad", "#63ab41"))
Super thankful for help!
I have tried tweaking scale_fill_manual without any good result, only resulting in changing the color of all bars.
答案1
得分: 1
可能以下内容:
Region <- c("北", "南", "东", "西", "北", "南", "东", "西")
q14 <- c("5", "5", "5", "5", "4", "4", "4", "4")
N <- c(4342, 5325, 654, 1231, 3453, 234, 345, 5634)
百分比 <- c(72, 71, 68, 67, 21, 20, 18, 17)
df <- data.frame(Region, q14, N, 百分比)
df <- mutate(df,
q14 = case_when(
Region == "北" &
q14 == "4" ~ "4 北",
Region == "北" ~ "5 北",
q14 == "4" ~ "4",
TRUE ~ "5"
)
)
ggplot(df, aes(
x = Region, y = 百分比,
fill = q14,
label = 百分比
)) +
geom_bar(stat = "identity") +
scale_fill_manual(
values =
c(
"4 北" = "#444444",
"5 北" = "#AAAAAA",
"4" = "#63ab41",
"5" = "#bbd6ad"
)
)
英文:
Possibly the following
Region <- c("north", "south", "east", "west", "north", "south", "east", "west")
q14 <- c("5", "5", "5", "5", "4", "4", "4", "4")
N <- c(4342, 5325, 654, 1231, 3453, 234, 345, 5634)
Percentage <- c(72, 71, 68, 67, 21, 20, 18, 17)
df <- data.frame(Region, q14, N, Percentage)
df <- mutate(df,
q14 = case_when(
Region == "north" &
q14 == 4 ~ "4 North",
Region == "north" ~ "5 North",
q14 == 4 ~ "4",
TRUE ~ "5"
)
)
ggplot(df, aes(
x = Region, y = Percentage,
fill = q14,
label = Percentage
)) +
geom_bar(stat = "identity") +
scale_fill_manual(
values =
c(
"4 North" = "#444444",
"5 North" = "#AAAAAA",
"4" = "#63ab41",
"5" = "#bbd6ad"
)
)
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论