R:绘制没有间断颜色的分组条形图

时间:2017-04-21 07:45:13

标签: r ggplot2 bar-chart axis-labels

鉴于此数据框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为红色 - 如此模型中所示: enter image description here

我的尝试产生某种怪异,并出现错误:

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")

enter image description here

所以,我最终会出现间歇性的颜色(蓝红蓝色......),轴和标题都消失了,我无法读取标签。我做错了什么?

2 个答案:

答案 0 :(得分:1)

不确定您是否希望远离基本图形,但无论如何,请参见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

enter image description here

这就是你想要的吗?

答案 1 :(得分:1)

使用基本图形(由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)

<强>输出

enter image description here