Re: [问题] 折线图+长条图呈现

楼主: celestialgod (天)   2017-06-14 20:00:17
我Update一下ggplot2的状态
ggplot2 2.2.0已经准许你这样做了
成果:http://imgur.com/7YIrEB8
程式好读版:https://pastebin.com/u6fCQKuy
程式码:
library(ggplot2)
library(dplyr)
numSamples <- 200L
DF <- data.frame(V1 = sample(1L:4L, numSamples, TRUE),
V2 = sample(1L:2L, numSamples, TRUE))
sum0 <- DF %>% group_by(V1) %>% summarise (mean = mean(V2), n = n())
ggplotColours <- function(n = 6, h = c(0, 360) + 15){
if ((diff(h) %% 360) < 1) h[2] <- h[2] - 360/n
hcl(h = (seq(h[1], h[2], length = n)), c = 100, l = 65)
}
transDblAxisForBar <- function(x, y) {
return((y - min(y)) / (max(y) - min(y)) * extendrange(x)[2])
}
cols <- ggplotColours(2)
ggplot(sum0, aes(V1, n)) +
geom_bar(position = "stack", stat = "identity", fill = cols[1]) +
geom_line(aes(x = V1, y = transDblAxisForBar(n, mean)),
col = cols[2], lwd = 1.5) +
scale_y_continuous("n",
sec.axis = sec_axis(~ . / extendrange(sum0$n)[2] * diff(range(sum0$mean))+
min(sum0$mean), name = "mean"))
※ 引述《sacidoO (阿骂)》之铭言:
: #更新 感谢版主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
: : [关键字]:
: : 选择性,也许未来有用

Links booklink

Contact Us: admin [ a t ] ucptt.com