簡體   English   中英

R:繪制沒有間歇顏色的分組條形圖

[英]R: plotting grouped bar plots without intermittent colors

給定此數據框df

City             P1     P2
A                11.7   NA
B                7.5    0.0
C                6.3    0.2
D                5.6    0.1
E                4.5    0.2
F                3.9    0.1
G                3.4    0.3
H                2.7    0.0
I                2.2    0.1
J                1.8    0.3
K                1.5    0.4
L                0.9    0.2
M                0.8    0.1

我想生成一個分組的條形圖,其中P1值分組在一起,而P2值分組在一起。 另外,我希望每組條具有相同的顏色-藍色為P1,紅色為P2-如下圖所示: 在此處輸入圖片說明

我的嘗試產生了某種怪胎和一個錯誤:

barplot(cbind(df$P1,df$P2), main="Grouped barplots", 
ylab="%", beside=TRUE, col=c("blue","red"),ylim=c(0,12),names.arg=df$City,las=2)
legend(13, 10, c("P1","P2"), cex=0.88, fill=c("blue","red"))



Error in barplot.default(cbind(df$P1, df$P2), : incorrect number of names
Traceback:

1. barplot(cbind(df$P1, df$P2), 
 .     main = "Grouped barplots", 
 .     ylab = "%", beside = TRUE, col = c("blue", "red"), ylim = c(0, 
 .         12), names.arg = df$City, las = 2)
2. barplot.default(cbind(df$P1, df$P2), 
 .     main = "Grouped barplots", 
 .     ylab = "%", beside = TRUE, col = c("blue", "red"), ylim = c(0, 
 .         12), names.arg = df$City, las = 2)
3. stop("incorrect number of names")

在此處輸入圖片說明

因此,我最終得到了斷斷續續的顏色(藍-紅-藍,...),軸和標題消失了,並且我無法閱讀標簽。 我究竟做錯了什么?

不確定是否要遠離基本圖形,但是無論如何,這里ggplot示例。

我也模擬了一些數據。

這是模擬數據:

    > dt <- data.table(City = LETTERS[1:10], P1 = sample(1:10, 10, replace = TRUE), P2 = sample(10:20, 10, replace = TRUE))
> dt
    City P1 P2
 1:    A  1 14
 2:    B  5 18
 3:    C  8 12
 4:    D  2 16
 5:    E  6 15
 6:    F 10 14
 7:    G  5 19
 8:    H  2 11
 9:    I  6 20
10:    J  4 19

這是代碼:

dt_m <- melt(dt, id.vars = "City")

g <- ggplot(data = dt_m)
g <- g + geom_col(aes(x = City, y = value, fill = as.factor(variable)))
g <- g + scale_fill_manual(values = c("blue", "red"), labels = c("P1", "P2"))
g <- g + labs(fill = "your variable")
g <- g + facet_wrap(~variable)
g

在此處輸入圖片說明

這是你所追求的嗎?

使用基本圖形(OP使用)組合兩個圖:

# Data
library(data.table)
set.seed(1)
dt <- data.table(City = LETTERS[1:10], P1 = sample(1:10, 10, replace = TRUE), P2 = sample(10:20, 10, replace = TRUE))

# Plots
par(mfrow = c(1, 2))
barplot(dt$P1, main = "P1", col = "blue", ylim = c(0, 20), names.arg = dt$City, las = 1, cex.axis =  1)
barplot(dt$P2, main = "P2", col = "red", ylim = c(0, 20), names.arg = dt$City, las = 1, cex.axis =  1)

輸出量

在此處輸入圖片說明

暫無
暫無

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

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