R:在同一图表上绘制不同大小的列

R: Plotting Columns of Different Sizes on Same Graph

我正在使用 R 编程语言。我有两个数据集:

第一个数据集:

my_data_1 <- data.frame(read.table(header=TRUE,
row.names = 1,
text="

  height    weight    age
1  13.14600 2882.7709  49
2  12.65080 3183.7991  48
3  13.84154 3138.2280  48
4  15.25780 2786.5297  49
5  15.01213 3006.9687  50
6  14.37567 3286.9644  50
7  12.99385 2881.7667  51
8  15.38893 2916.1883  50
9  14.80093 2791.7292  49
10 15.40423 2427.7706  50
11 17.55129  630.8886  20
12 18.34758 1076.6810  19
13 16.37789 1778.5550  20
14 14.98782 1401.4328  17
15 17.40527  361.3323  20
16 16.53979  869.5829  21
17 16.61986 1712.1686  19
18 17.78508 1961.6090  20
19 16.83144 1043.5052  19
20 18.66166  360.3037  20
                      
"))

第二个数据集:

prior_age = rnorm(100000, 50,5)
   prior_height = rnorm(100000, 17,1)
  prior_weight = rnorm(100000, 3000, 200)

my_data_2 = data.frame(prior_age, prior_height, prior_weight)

(基于这个 post 的答案:ggplot combining two plots from different data.frames)我试图在同一张图上绘制来自两个数据集的高度变量的“密度”。但是,两个数据集的行数不同。

我在 R 中尝试了以下代码:

    library(ggplot2)
   ggplot() + 
    geom_density(data=my_data1, aes(x=height), color='green') + 
    geom_density(data=my_data2, aes(x=prior_height), color='red')

但这会产生以下错误:

Error: Aesthetics must be either length 1 or the same as the data (20): x

有人可以告诉我如何解决这个问题吗?

谢谢!

好吧,根据您提供的代码,我不需要更改数据的形状。只需使用 guides(... = guide_legend(title = ...))scale_colour_discrete 手动更改图例的组件。

ggplot() + 
  geom_density(data=my_data_1, aes(x=height), color='green') + 
  stat_density(data = my_data_1, aes(x=height, colour="red"), geom="line",position="identity") + 
  geom_density(data=my_data_2, aes(x=prior_height), color='red') + 
  stat_density(aes(x=prior_height, colour='green'), geom="line",position="identity") +
  guides(colour = guide_legend(title = "new title"),) +
  scale_colour_discrete(labels = c( "prior", "measurements"))