簡體   English   中英

R:ggplot2在一個圖中繪制幾個數據幀

[英]R : ggplot2 plot several data frames in one plot

我在ggplot2上停留了一點,試圖在一個圖中繪制多個數據幀。

我在這里有幾個數據框,我僅介紹兩個示例。

數據幀具有相同的標頭,但不同。 假設我要計算2盒中的球數。

name=c('red','blue','green','purple','white','black')
value1=c(2,3,4,2,6,8)
value2=c(1,5,7,3,4,2)

test1=data.frame("Color"=name,"Count"=value1)
test2=data.frame("Color"=name,"Count"=value2)

我想做的是繪制我的數量的條形圖。 目前我所做的是:

(plot_test=ggplot(NULL, aes(x= Color, y=Count)) + 
    geom_bar(data=test1,stat = "identity",color='green')+
    geom_bar(data=test2,stat = "identity",color='blue')
)

問題是我的地塊重疊了

我想讓x = Color和y = Count,以及test1旁邊的test2數據框的條形圖。 這里有重疊的自己。 因此,我將在x中使用兩次相同的名稱,但我想用幾種顏色繪制數據框,並在圖例中得到該名稱。

例如,“綠色條” = test1“藍色條” = test2

感謝您的時間和幫助。

最好的祝福

嘗試這個:

name=c('red','blue','green','purple','white','black')
value1=c(2,3,4,2,6,8)
value2=c(1,5,7,3,4,2)

test1=data.frame("Color"=name,"Count"=value1)
test2=data.frame("Color"=name,"Count"=value2)

test1$var <- 'test1'
test2$var <- 'test2'

test_all <- rbind(test1,test2)


(plot_test=ggplot(data=test_all) + 
  geom_bar(aes(x=Color,y=Count,color=var),
           stat = "identity", position=position_dodge(1))+
  scale_color_manual(values = c('green', 'blue'))
)

您在這里有兩個選擇:

調整條的大小和位置

ggplot(NULL, aes(x= Color, y=Count)) + 
geom_bar(data=test1, aes(color='test1'), stat = "identity",
         width=.4, position=position_nudge(x = -0.2)) +
geom_bar(data=test2, aes(color='test2'), stat = "identity", 
         width=.4, position=position_nudge(x = 0.2))

在此處輸入圖片說明 或者我建議將兩個數據框連接在一起,然后繪制

library(dplyr)
test1 %>% 
  full_join(test2, by = 'Color') %>% 
  data.table::melt(id.vars = 'Color') %>% 
  ggplot(aes(x= Color, y=value, fill = variable)) + 
  geom_bar(stat = "identity", position = 'dodge')

在此處輸入圖片說明

這將完成您嘗試做的事情:

balls <- data.frame(
  count = c(c(2,3,4,2,6,8),c(1,5,7,3,4,2)),
  colour = c(c('red','blue','green','purple','white','black'),c('red','blue','green','purple','white','black')),
  box = c(rep("1", times = 6), rep("2", times = 6))
)

ggplot(balls, aes(x = colour, y = count, fill = box)) +
  geom_col() +
  scale_fill_manual(values = c("green","blue"))

這樣做更好,因為它有助於比較箱數:

ggplot(balls, aes(x = colour, y = count)) +
  geom_col() +
  facet_wrap(~ box, ncol = 1, labeller = as_labeller(c("1" = "Box #1", "2" = "Box #2")))

暫無
暫無

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

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