如何用外部变量标记图
How to label plot with external variables
假设我有以下数据:
require(reshape2)
require(ggplot2)
data <- data.frame(id=seq(1,5,1), var1=c(10,3,5,7,8), label1=c(2,2,2,3,2), var2=c(12, 6, 6, 8, 6), label2=c(7,7,6,7,5))
我使用 melt
重塑数据以为 ggplot
做好准备。
data_graph <- melt(data[,c(1,2,4)], id="id")
然后我绘制它,用值标记每个点:
ggplot(data=data_graph, aes(y=value, x=id, group=variable, col=variable)) +
geom_line(size=2) + geom_point() +
geom_text(aes(label=value), size=5, hjust=-.6, vjust=1.5)
然而,我实际上想要 label1
向量标记对应于 var1
的行,并且类似于 label2
和 var2
。我该怎么做?
我认为要解决您的问题,您需要为 ggplot2 准备一个不同的 data.frame,一个带有 id、变量、标签和值。
# dataset for var1
df1 <- cbind(data[,c(1,3,2)], 'var1')
colnames(df1) <- c('id', 'label', 'value', 'variable')
# dataset for var2
df2 <- cbind(data[,c(1,5,4)], 'var2')
colnames(df2) <- c('id', 'label', 'value', 'variable')
# putting them together
data_graph <- rbind(df1,df2)
现在你的图可以这样生成了:
gplot(data=data_graph, aes(y=value, x=id, group=variable, col=variable)) +
geom_line(size=2) + geom_point() +
geom_text(aes(label=label), size=5, hjust=-.6, vjust=1.5)
这是结果,标签列中的值作为数据点的标签:
假设我有以下数据:
require(reshape2)
require(ggplot2)
data <- data.frame(id=seq(1,5,1), var1=c(10,3,5,7,8), label1=c(2,2,2,3,2), var2=c(12, 6, 6, 8, 6), label2=c(7,7,6,7,5))
我使用 melt
重塑数据以为 ggplot
做好准备。
data_graph <- melt(data[,c(1,2,4)], id="id")
然后我绘制它,用值标记每个点:
ggplot(data=data_graph, aes(y=value, x=id, group=variable, col=variable)) +
geom_line(size=2) + geom_point() +
geom_text(aes(label=value), size=5, hjust=-.6, vjust=1.5)
然而,我实际上想要 label1
向量标记对应于 var1
的行,并且类似于 label2
和 var2
。我该怎么做?
我认为要解决您的问题,您需要为 ggplot2 准备一个不同的 data.frame,一个带有 id、变量、标签和值。
# dataset for var1
df1 <- cbind(data[,c(1,3,2)], 'var1')
colnames(df1) <- c('id', 'label', 'value', 'variable')
# dataset for var2
df2 <- cbind(data[,c(1,5,4)], 'var2')
colnames(df2) <- c('id', 'label', 'value', 'variable')
# putting them together
data_graph <- rbind(df1,df2)
现在你的图可以这样生成了:
gplot(data=data_graph, aes(y=value, x=id, group=variable, col=variable)) +
geom_line(size=2) + geom_point() +
geom_text(aes(label=label), size=5, hjust=-.6, vjust=1.5)
这是结果,标签列中的值作为数据点的标签: