作者sacidoO (阿骂)
看板R_Language
标题Re: [问题] 折线图+长条图呈现
时间Tue Jun 13 12:16:21 2017
#更新 感谢版主c大各种code详解 及G大还有Andrew大的帮忙!已经有解了
更新方法一於置底
借用这个标题 跟原po有一样的问题 试了几个帮法 但是都不成功.........
不知道版上有没有人能有方法解决两种方法使其更优......感谢了!
[程式范例]
#data: 用c大分享的 code
library(dplyr)
ngrp <- 2L
numSamples <- 200L
DF <- data.frame(V1 = sample(1L:3L, numSamples, TRUE), V2 = sample(1L:2L,
numSamples, TRUE),
V3 = rnorm(numSamples), V4 = rnorm(numSamples), V5 =
rnorm(numSamples))
#sum statistics
sum0<-DF %>% group_by(V1) %>% summarise (mean=mean(V2),n=n())
#方法一: bar chart 不在节点上,看起来怪怪的
par(mar=c(4,4.5,4,4))
barplot(sum0$n,ylim=c(0,max(sum0$n)+0.1*max(sum0$n)),
yaxt="n",width=0.2,space=2)
axis(side=4)
mtext("Count", side=4, line=1.8)
par(new=T)
plot(sum0$V1,sum0$mean, xlab="cartegpory level", ylim=c(0,2), ylab="")
mtext("Group mean",side=2, line=1.8)
lines(sum0$V1,sum0$mean, type="o")
#方法二 使用ggpltot, 但是无法让两图在同一图上...
library(ggplot2)
#frequency plot
g.botton<-ggplot()+geom_bar(data=sum0,aes(x=V1, y=n), stat="identity")+
labs(y="Counts")+
theme_classic()
#line plot
g.top<-ggplot()+geom_line(data=sum0, aes(x=V1, y=mean,
group=1))+geom_point(data=sum0,aes(x=V1,y=mean, group=1))+
scale_y_continuous(limits = c(0,2),position="right")+
labs(y="Group mean")+
theme_classic()
print(g.bottom) #vp ?
print(g.top) #vp?
※ 引述《samex4x4 (Same)》之铭言:
: [问题类型]:
:
: 程式谘询(我想用R 做某件事情,但是我不知道要怎麽用R 写出来)
:
: [软体熟悉度]:
: 入门(写过其他程式,只是对语法不熟悉)
: [问题叙述]:
: 想询问是否有办法同时画出长条图和摺线图在一张图表上?
: 两者是不同的数值(取不同栏位)
: 大概是长这样
: http://imgur.com/b5XELZF.jpg
: 谢谢QQ
: [程式范例]:
:
:
: [环境叙述]:
:
: 3.3.2
:
: [关键字]:
:
: 选择性,也许未来有用
:
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 72.195.237.4
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/R_Language/M.1497327383.A.763.html
1F:推 Goldexp: 方法二可以试试看gridExtra这个package 06/13 13:12
2F:→ Goldexp: grid.arrange(g.bottom, g.top, ncol = 1) 06/13 13:13
感谢G大分享此方法 试过之後 貌似grid.arrange只会将
图合并成上下图...
3F:→ andrew43: barplot()的回传值会直接告诉你每个柱的x轴位置 06/14 01:13
4F:→ andrew43: 你看看 y <- barplot(...) 之後 y 是什麽? 06/14 01:13
5F:→ andrew43: 就可以解决没有对齐的问题了。 06/14 01:13
感谢andrew大提醒! 更新修改方法於下:
#更新:加入xlim可解
par(mar=c(4,4.5,4,4))
Y<-barplot(sum0$n,sum0$V1,ylim=c(0,max(sum0$n)+0.1*max(sum0$n)),
yaxt="n",width=0.2,space=2,xlim=c(min(Y)-0.1*max(Y),max(Y)+0.1*max(Y)))
axis(side=4)
mtext("Count", side=4, line=1.8)
par(new=T)
plot(Y,sum0$mean, xlab="cartegpory level", ylim=c(0,2),
ylab="",xlim=c(min(Y)-0.1*max(Y),max(Y)+0.1*max(Y)),xaxt="n")
mtext("Group mean",side=2, line=1.8)
lines(Y,sum0$mean,
type="o",ylab="",xlim=c(min(Y)-0.1*max(Y),max(Y)+0.1*max(Y)),xaxt="n")
图范例:
http://imgur.com/XTNEEVL
再次感谢大家的时间与帮忙! 谢谢!
※ 编辑: sacidoO (72.195.237.4), 06/14/2017 12:58:07
6F:推 Goldexp: 哈 搞懂你的问题了 原来不是要把两个图摆在一起 06/14 14:13
7F:→ Goldexp: hadley在10年时在stackoverflow说ggplot2没办法做这种图 06/14 14:16
8F:→ celestialgod: 怎麽可能ggplot2不行,跟lattice一样是grid-based, 06/14 19:13
9F:→ celestialgod: 只是没人做而已 06/14 19:13
10F:→ celestialgod: ggplot2已经可以这样做了,我更新在我回覆的文章中 06/14 20:01
11F:推 locka: 应该是说当时hadley说这种图不符合ggplot2的设计哲学 06/14 20:02
13F:→ celestialgod: 此一时彼一时阿(摊手 06/14 20:05