请问如何在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))
在此梯形图中:
关于package plotrix的一些信息,但是我似乎找不到详细信息。
答案 0 :(得分:0)
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
答案 1 :(得分:0)
感谢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轴,其在上面的代码中已注释掉。