簡體   English   中英

R, ggplot2 添加具有不同數據框(不同大小)的圖例

[英]R, ggplot2 add legend with different data frames (of different sizes)

我正在嘗試使用 ggplot2 制作一個簡單的 geom_point 圖,但我無法顯示圖例。 我有兩個不同長度的數據框(~2000 行 vs~6000 行)。

我曾嘗試添加諸如 'scale_shape_manual(values=c(21, 23)' 之類的東西以使其彈出,但這沒有用。我也嘗試將 'shape = 21' 添加到 aes 並將 'shape = 23' 添加到aes 用於它們各自的 geom_point 調用,但我收到錯誤“錯誤:提供給離散比例的連續值”。感謝您的幫助!請參閱下面的代碼示例:

x1 = c(0, 1, 2, 3, 4)
y1 = c(0.44, 0.64, 0.77, 0.86, 0.91)
x2 = c(0, 1)
y2 = c(0.42, 0.61)
df1 = data.frame(x1, y1)
df2 = data.frame(x2, y2)

g<- ggplot(df1, aes(x = (df1[,1]), y = (df1[,2]*100))) +
  geom_point(colour = 'black', size = 5, fill = 'blue', shape = 21) +
  geom_point(data = df2, aes(x = df2[,1], y = (df2[,2]*100)), 
             colour = 'black', size = 4, fill = 'white', shape = 23) +
  xlab("Consecutive Dry Years") + ylab("Percent") + ggtitle("Plot") +
  scale_y_continuous(limits=c(0, 100)) +
  scale_x_continuous(breaks=0:20) +
  scale_shape_manual(values=c(21, 23), 
                     name="My Legend",
                     labels=c("Simulated", "Historical")) +
  #   scale_fill_manual(values=c('blue', 'white'), 
  #                      name="My Legend",
  #                      labels=c("Simulated", "Historical")) +
  #   scale_colour_manual(values=c('black', 'black'), 
  #                     name="My Legend",
  #                     labels=c("Simulated", "Historical")) +
  theme_bw()
g

對於我的 ggplotting,我總是將我的數據放入一個數據框中。 我記得有人說在幾何圖形中指定不同的顏色存在沖突。 我認為這段代碼給了你這個想法:

df3 = data.frame(type=c(rep("sim",5), rep("his",2)), x = c(x1,x2), y=c(y1,y2))
g = ggplot(df3, aes(x=x,y=y*100)) + geom_point(aes(color=type)) + geom_line(aes(color=type)) +
  xlab("Consecutive Dry Years") + ylab("Percent") + ggtitle("Plot") +
  scale_y_continuous(limits=c(0, 100))
g

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM