## 可以用 "binwidth = x" to 调整bar的宽度
csub <- subset(climate, Source == "Berkeley" & Year >= 1900) #选取Source == "Berkeley" & Year >= 1900的数据
csub$pos <- csub$Anomaly10y >= 0 #创建csub$pos 变量为csub$Anomaly10y >= 0 的数据
ggplot(csub, aes(x = Year, y = Anomaly10y, fill = pos)) + geom_bar(stat = "identity",
position = "identity") #正负用不同颜色表示,还挺漂亮的呵,可是有点感觉不对啊,你有没有发现?
在我们日常生活中,红色一般象征正,暖色调嘛,蓝色一般表示负,冷色调呀,有没有?你家电线红色是不是火线,红色是不是正极,虽然上图没有错,但是我们想换一下,正的为红色,负的为蓝色咋办?而且我不想要旁边的图例了,怎么办?
用 scale_fill_manual() 和 guide=FALSE
ggplot(csub, aes(x = Year, y = Anomaly10y, fill = pos)) + geom_bar(stat = "identity",
position = "identity", colour = "black", size = 0.25) + scale_fill_manual(values = c("#CCEEFF",
"#FFDDDD"), guide = FALSE)
这应该前面讲过,width = xx来控制
ggplot(pg_mean, aes(x = group, y = weight)) + geom_bar(stat = "identity")
ggplot(pg_mean, aes(x = group, y = weight)) + geom_bar(stat = "identity", width = 0.5)
ggplot(pg_mean, aes(x = group, y = weight)) + geom_bar(stat = "identity", width = 1)
那如果是一组一组的条形图我想让他们中间有点缝隙怎么办?用position = position_dodge(0.7)来控制
ggplot(cabbage_exp, aes(x = Date, y = Weight, fill = Cultivar)) + geom_bar(stat = "identity",
width = 0.5, position = "dodge")
ggplot(cabbage_exp, aes(x = Date, y = Weight, fill = Cultivar)) + geom_bar(stat = "identity", width = 0.5, position = position_dodge(0.7))
ggplot(cabbage_exp, aes(x = Date, y = Weight, fill = Cultivar)) + geom_bar(stat = "identity")
有没有发现,右边图例红色在上,而图形红色在下?修改一下
ggplot(cabbage_exp, aes(x = Date, y = Weight, fill = Cultivar)) + geom_bar(stat = "identity") +
guides(fill = guide_legend(reverse = TRUE))
添加标签
给每一个bar添加一个标签,表示其具体数值是多少.这里标签使用的是weight变量的数值,因为纵坐标本来就是weight
vjust表示距离bar的顶端有多少,你也可以设置成负数让标签在bar上面
ggplot(cabbage_exp, aes(x = interaction(Date, Cultivar), y = Weight)) + geom_bar(stat = "identity") + geom_text(aes(label = Weight), vjust = 1.5, colour = "white")
ggplot(cabbage_exp, aes(x = interaction(Date, Cultivar), y = Weight)) + geom_bar(stat = "identity") + geom_text(aes(label = Weight), vjust = -0.2,color="red")
堆栈的条形图加标签:需要另一个包plyr
library(plyr)
ce <- arrange(cabbage_exp, Date, Cultivar) #根据Date,Cultivar 排序
ce <- ddply(ce, "Date", transform, label_y = cumsum(Weight)) #增加新变量label_y
ggplot(ce, aes(x = Date, y = Weight, fill = Cultivar)) + geom_bar(stat = "identity") + geom_text(aes(y = label_y, label = Weight), vjust = 1.5, colour = "white")
这就是部分条形图的深加工,我们虽然展示了很多功能,但在实际中我们还需要将这些功能组合。
推荐阅读:
http://www.ppvke.com/10380.htmlPPV课视频教程
http://www.ppvke.com/10217.htmlPPV课视频教程
PPV课整理文章,未经允许严禁转载
原文始发于微信公众号(PPV课数据科学社区):数据挖掘知识脉络与资源整理(九)–柱形图
原创文章,作者:ppvke,如若转载,请注明出处:http://www.ppvke.com/archives/13826