為一項任務設定了這個問題 - 但我以前從未使用過 R - 任何幫助表示贊賞。非常感謝。
問題:制作散點圖來比較 1950 年至 2019 年巴西和阿根廷的二氧化碳排放量……我可以為巴西得到它,但不知道如何添加阿根廷。我想我必須對 geom_point 和 filter 做些什么?
df%>%
filter(Country=="Brazil", Year<=2019 & Year>=1950) %>%
ggplot(aes(x = Year, y = CO2_annual_tonnes))
geom_point(na.rm =TRUE, shape=20, size=2, colour="green")
labs(x = "Year", y = "CO2Emmissions (tonnes)")
uj5u.com熱心網友回復:
答案取決于您要做什么,但通常通過應用美學(顏色、形狀等)或刻面來向散點圖添加另一個維度,其中您已經清楚x并且y維度。
在這兩種方法中,您實際上都不想過濾資料。您可以使用美學或分面以某種方式“過濾”并根據country資料集中的列適當地映射資料。如果您的資料集包含的國家/地區多于阿根廷和巴西,您將需要過濾以僅包含這些國家/地區,因此:
your_filtered_df <- your_df %>%
dplyr::filter(Country %in% c("Argentina", "Brazil"))
刻面
分面是另一種說法,您想將一個地塊分成兩個單獨的地塊(一個用于阿根廷,一個用于巴西)。每個圖將具有相同的美感(看起來相同),但將具有適當的“過濾”資料集。
在您的情況下,您可以嘗試:
your_filtered_df %>%
ggplot(aes(x = Year, y = CO2_annual_tonnes))
geom_point(na.rm =TRUE, shape=20, size=2, colour="green")
facet_wrap(~Country)
美學
在這里,您有很多選擇。這個想法是你告訴將點幾何中各個點ggplot2的外觀映射到 中指定的值your_filtered_df$Country。您可以通過為geom_point()inside放置美學引數之一來做到這一點aes()。shape=例如,如果您使用,它可能如下所示:
your_filtered_df %>%
ggplot(aes(x = Year, y = CO2_annual_tonnes))
geom_point(aes(shape=Country), na.rm =TRUE, size=2, colour="green")
這應該顯示一個圖,該圖為對應于國家名稱的點創建了一個圖例和兩個不同的形狀。這是非常重要的是要記住,當你把一個審美喜歡shape或color或size里面aes(),你一定不是也有它外面。因此,這將正確運行:
geom_point(aes(colour=Country), ...)
但這不會:
geom_point(aes(colour=Country), colour="green", ...)
當一種美學在外部時,它會覆寫aes(). 第二個仍然將所有點顯示為綠色。
不要這樣做......但它有效
OP 發表了一條評論,指出教授的一些額外提示,即:
我們在問題“您可以在 geom_point 物件中嵌入管道過濾器函式”中得到提示
我相信他們指的是最終……非常糟糕的產生積分的方式。這種方法需要你有兩個 geom_point()物件,并為每個物件發送一個不同的過濾資料集。您可以通過訪問data=每個geom_point()物件中的引數來做到這一點。這種方法有很多問題,包括缺少生成的圖例,但如果你必須這樣做......這里是:
# painful to write this. it goes against all good practices with ggplot
your_filtered_df %>%
ggplot(aes(x = Year, y = CO2_annual_tonnes))
geom_point(data=your_filtered_df %>% dplyr::filter(Country=="Argentina"),
color="green", shape=20)
geom_point(data=your_filtered_df %>% dplyr::filter(Country=="Brazil"),
color="red", shape=20)
You should probably see why this is not a good convention. Think about what you would do for representing 50 different countries... the above codes or methods would work, but with this method, you would have 50 individual geom_point() objects in your plot... ugh. Don't make a typo!
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/343315.html
