我正在使用ggplot在同一图上绘制两组数据。我已经为每个数据集指定了颜色,但是在生成点图时不会出现图例。
我该怎么做才能手动添加图例?
# Create an index to hold values of m from 1 to 100
m_index <- (1:100)
data_frame_50 <- data(prob_max_abs_cor_50)
data_frame_20 <- data.frame(prob_max_abs_cor_20)
library(ggplot2)
plot1 <- ggplot(data_frame_50, mapping = aes(x = m_index,
y = prob_max_abs_cor_50),
colour = 'red') +
geom_point() +
ggplot(data_frame_20, mapping = aes(x = m_index,
y = prob_max_abs_cor_20),
colour = 'blue') +
geom_point()
plot1 + labs(x = " Values of m ",
y = " Maximum Absolute Correlation ",
title = "Dot plot of probability")
答案 0 :(得分:0)
首先,我建议您稍微整理一下ggplot
代码。这等效于您发布的代码;
ggplot() +
geom_point(data = data_frame_50, aes(x = m_index, y = prob_max_abs_cor_50,
colour = 'red')) +
geom_point(data = data_frame_20, aes(x = m_index, y = prob_max_abs_cor_20,
colour = 'blue')) +
labs(x = " Values of m ", y = " Maximum Absolute Correlation ",
title = "Dot plot of probability")
这里不会显示图例,因为您正在绘制不同的数据集,每个数据集中只有一个类别。您需要具有一个数据集,该数据集的列将数据分组(即20
或50
)。因此,使用一些示例数据,这相当于您要绘制的内容,并且ggplot不会提供图例;
ggplot() +
geom_point(data = iris, aes(x = Sepal.Length, y = Petal.Width), colour = 'red') +
geom_point(data = iris, aes(x = Sepal.Length, y = Petal.Length), colour = 'blue')
如果要按类别着色,请在colour
调用中加入一个aes
自变量;
ggplot() +
geom_point(data = iris, aes(x = Sepal.Length, y = Petal.Width,
colour = factor(Species)))
看看iris
数据集,以了解如何调整数据形状。很难提供准确的建议,因为您尚未提供有关数据外观的想法,但是类似的事情可能有用;
df.20 <- data.frame("m" = 1:100, "Group" = 20, "Numbers" = prob_max_abs_cor_20)
df.50 <- data.frame("m" = 1:100, "Group" = 50, "Numbers" = prob_max_abs_cor_50)
df.All <- rbind(df.20, df.50)