簡體   English   中英

如何使用ggplot根據R中df的colors列填充堆積條plot的colors

[英]How to fill colors of stacked bar plot depending on colors column of df in R using ggplot

我正在嘗試使用我在 df 的“col”列中分配的 colors 創建堆積條 plot。 我嘗試使用 scale_color_identity() 來做到這一點。

colors是使用下面的代碼隨機分配的,因為我一共有300個國家,無法手動分配colors。

color <- grDevices::colors()[grep('gr(a|e)y', grDevices::colors(), invert = T)]
colors <- fread("country_color.txt", header = TRUE, fill = TRUE)
colors[,col := sample(color, nrow(colors))]

其中文件 country_color.txt 只有我的 df 所有國家的名稱。

在使用新顏色值 ( colors ) 和我的數據 ( producer_countries ) 的 rest 進行 left_join 后,我的 df 看起來像這樣。

Country    year   total_value  col    
USA      1995   100        green
China    1995   120        red
Other    1995   150        brown
USA      2000   188        green
China    2000   177        red
Other    2000   320        brown

這是 plot 的代碼,但它以某種方式沒有使用 df 中分配的 colors。

ggplot(producer_countries, aes(fill=reorder(Country, total_value), y=total_value, x=year)) +     
  geom_bar(position="stack", stat="identity",  color = "black", aes(colour=col))+
  scale_color_identity() +
  xlab("Year") +
  ylab("Quantity)

謝謝!

您應該在geom_bar()調用中使用aes(fill=col) ,然后按如下方式使用scale_fill_identity()

ggplot(producer_countries, aes(fill=reorder(Country, total_value), y=total_value, x=year)) +     
  geom_bar(position="stack", stat="identity",  color = "black", aes(fill=col))+
  scale_fill_identity() +
  xlab("Year") +
  ylab("Quantity")

暫無
暫無

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

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