我正在嘗試使用我在 df 的“col”列中分配的顏色創建堆積條形圖。我嘗試使用 scale_color_identity() 來做到這一點。
顏色是使用以下代碼隨機分配的,因為我總共有 300 個國家,無法手動分配顏色。
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 )執行 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
這是情節的代碼,但它以某種方式不使用 df 中分配的顏色。
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)
謝謝!
uj5u.com熱心網友回復:
你應該aes(fill=col)在geom_bar()呼叫中使用,然后使用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")
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/534795.html
標籤:r图表2
上一篇:將控制器中的陣列顯示為視圖中的表
