簡體   English   中英

如何根據變量用特定的調色板填充條形 plot?

[英]How do I fill a bar plot with a specific colour palette according to the variables?

嘗試通過創建自己的調色板來分配每種可變顏色,但有些顏色會混淆。 關於我應該如何解決這個問題的任何想法?

cor.partidos <- c(
  `ps` = "#f71b75",
  `psd` = "#ef6438",
  `pcp-pev` = "#ff001d",
  `pan` = "#71af64",
  `outros` = "#f71b75",
  `nulos` = "#565557",
  `brancos` = "#aaa8ad",
  `l` = "#f71b75",
  `il` = "#f71b75",
  `ch` = "#393195",
  `cds-pp` = "#1192d8",
  `be` = "#b40020",
  `a` = "#f71b75") 

#test graph
bars <- ggplot(leg19, aes(x = partido, y = votos)) +
  geom_bar(stat="identity", 
           position="identity", 
           fill = cor.partidos) +
  geom_hline(yintercept = 0, size = 1, colour="#333333") +
  bbc_style() +
  theme(axis.text=element_text(size=10))+
  labs(subtitle = "Resultados Legislativas 2019",
       ylab = "votos")

酒吧

用 mwe 更新

如果托盤中的變量與 dataframe 的順序相同,它將起作用,但如果將其混合一下,它將不起作用。 將其更改為aes(fill = cor.partidos)將不起作用:(

test.pallet <- c(
  `pink` = "#f71b75",
  `orange` = "#ef6438",
  `green` = "#71af64",
  `red` = "#ff001d",
  `other pink` = "#f71b72")

test.datafrane <- data_frame(
  name = c("pink","orange","red","green","other pink"),
  value = c(1,2,3,4,5)
)
test.datafrane$value <- as.numeric(test.datafrane$value)

test.graph <- ggplot(test.datafrane, aes(x = name, y = value)) +
  geom_bar(stat="identity", 
           position="identity", 
           fill = test.pallet)
test.graph

測試圖

帶有 aes 的 test.graph(fill = test.pallet)

正如我在評論中建議的那樣,您可以通過將您的分類變量映射到 aes() 內的fill上並使用scale_fill_manual來實現您的結果:

test.pallet <- c(
  `pink` = "#f71b75",
  `orange` = "#ef6438",
  `green` = "#71af64",
  `red` = "#ff001d",
  `other pink` = "#f71b72")

test.datafrane <- data.frame(
  name = c("pink","orange","red","green","other pink"),
  value = c(1,2,3,4,5)
)
test.datafrane$value <- as.numeric(test.datafrane$value)

library(ggplot2)

test.graph <- ggplot(test.datafrane, aes(x = name, y = value, fill = name)) +
  geom_bar(stat="identity", 
           position="identity") +
  scale_fill_manual(values = test.pallet)
test.graph

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM