请问如何在R中制作梯形图。这是一个数据示例:
d <- data.frame("Subject" = 1:10,
"Group" = c(rep(1, 6), rep(2, 4)),
"Gender" = c(rep("male" ,2), rep("female", 6), rep("male", 2)),
"Y1" = rnorm(10, 100, 30),
"Y2" = rnorm(10, 3000, 1000))
在这个梯形图中:
有一些关于包plotrix但我似乎无法找到细节。
ggplot2库是如此灵活,我会使用它,而不是寻找一个固定的例行程序。这里的代码包含梯形图的基础知识。查看secondary axes和changing the scales颜色和线型等现有文档。我要离开这个,所以你的帖子感觉就像是在问一个有针对性的问题(并且不会被标记为a request for a code writing service)。
下面的重要步骤实际上是在图形调用之前。将“宽”格式更改为“长”。
library(magrittr)
library(ggplot2)
set.seed(100)
d <- data.frame(
Subject = 1:10,
Group = c(rep(1, 6), rep(2, 4)),
Gender = c(rep("male" ,2), rep("female", 6), rep("male", 2)),
Y1 = rnorm(10, 100, 30),
Y2 = rnorm(10, 3000, 1000)
)
d_long <- d %>%
tidyr::gather(key=Time, value=Score, -Subject, -Group, -Gender) %>%
dplyr::mutate(
Group = factor(Group)
)
ggplot(d_long, aes(x=Time, y=Score, group=Subject, linetype=Group, color=Gender)) +
geom_line()
结果
> head(d_long)
Subject Group Gender Time Score
1 1 1 male Y1 84.93423
2 2 1 male Y1 103.94593
3 3 1 female Y1 97.63249
4 4 1 female Y1 126.60354
5 5 1 female Y1 103.50914
6 6 1 female Y1 109.55890
谢谢wibeasley的意见!这非常有帮助。然而,我使用以下代码生成我的结果。
# Melt dataset for plot:
library(reshape)
melted_data<-melt(d, id.vars=c("Subject","Group","Sex"),measure.vars= c("Y1","Y2"))
melted_data$Group<-as.factor(melted_data$Group)
# calcuate R2 per Group and Sex combination
require(plyr)
func <- function(xx)
{ return(data.frame(R2 = round (cor(xx$Y1, xx$Y2),6)))}
CorrDataset<-ddply(d, .(Group,Sex), func)
# plot:
library(gridExtra)
library(ggplot2)
set.seed(1)
p <-ggplot(melted_data, aes(x=variable, y=value, group=Subject, linetype=Group, color=Sex)) +
geom_line(size=1)
#p <- p + scale_y_continuous(sec.axis = sec_axis(~ scale(.), name = "Y2"))
p+theme(legend.position="top",
axis.line.x = element_line(color="black", size = 2),
axis.line.y = element_line(color="black", size = 2),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
panel.background = element_blank())+
annotation_custom(tableGrob(CorrDataset,rows = rownames(CorrDataset)), ymin=4000, ymax=4000)
请注意:对于第二个Y轴,它在上面的代码中注释掉了。