簡體   English   中英

在 R 中無法繪制圖表

[英]Trouble plotting graph in R

我在 R 中使用 palmer penguins 數據集,目前無法使用匯總的 function 進行繪圖。 代碼如下,任何提示都會有所幫助。 我還在下面附上了預期圖形 output 的圖片。

在此處輸入圖像描述

ex1 <- penguins %>%
  group_by(sex,species) %>%
  summarise(fmean_body = mean(body_mass_g)) %>%
  

ggplot(ex1, aes(x = year))+
  geom_line(aes(x = year-2000, y = body_mass_g/1000, linetype = sex))+
  theme_bw()+
  facet_wrap(~species)+
  labs(title="Average Body Mass Over Time", 
       y="Body Mass (in kg)")

error: 
`summarise()` has grouped output by 'sex'. You can override using the `.groups` argument.
Error: Mapping should be created with `aes()` or `aes_()`.

我認為主要問題是 pipe 運算符已留在行尾,上面有匯總 function。

The pipe operator tells R to expect another line of code where the first argument will me the object created so far so ggplot has an additional argument with ex1 now in the position of the mapping argument.

這應該更容易發現代碼中的其他錯誤。

年份參數目前被匯總 function 刪除。 我們對所有值取平均值,因此 ex1 中不再存在年份,我們可以通過將年份添加到 group_by function 來解決這個問題。

此外,body_mass_g 已被 fmean_body 替換,因此當我們在 geom_line 中選擇 y 軸時,我必須替換名稱。

library(palmerpenguins)
library(tidyverse)

ex1 <- penguins %>%
  # Added group_by year
  group_by(sex,species, year) %>%
  # Removed unused pipe operator
  summarise(fmean_body = mean(body_mass_g))
#> `summarise()` has grouped output by 'sex', 'species'. You can override using the `.groups` argument.


ggplot(ex1, aes(x = year))+
  # Replaced the body_mass_g variable with fmean_body
  geom_line(aes(x = year-2000, y = fmean_body/1000, linetype = sex))+

  theme_bw()+

  facet_wrap(~species)+

  labs(title="Average Body Mass Over Time", 

       y="Body Mass (in kg)")
#> Warning: Removed 2 row(s) containing missing values (geom_path).

reprex package (v2.0.0) 於 2021 年 4 月 4 日創建

為了使其與預期圖像更加一致,我們將不得不進行更多更改,其中包括向繪圖添加形狀參數、刪除 NA 值以及使用比例尺 package 修改軸標簽。

library(palmerpenguins)
library(tidyverse)
library(scales)

ex1 <- penguins %>%
  group_by(sex,species, year) %>%
  summarise(fmean_body = mean(body_mass_g)) %>% 
  # Removed/Ignored NA values
  filter(!is.na(sex))
#> `summarise()` has grouped output by 'sex', 'species'. You can override using the `.groups` argument.
  

ggplot(ex1, aes(x = year))+

  geom_line(aes(x = year-2000, y = fmean_body/1000, linetype = sex)) +
  #Added points to the plot
  geom_point(aes(x = year-2000, y = fmean_body/1000, shape = sex)) +
  #Modified xticks
  scale_x_continuous(breaks = c(7, 8, 9), labels = label_comma(accuracy = 1)) +

  theme_bw()+

  facet_wrap(~species)+

  labs(title="Average Body Mass Over Time", 

       y="Body Mass (in kg)", shape = "Sex", linetype = "Sex")

reprex package (v2.0.0) 於 2021 年 4 月 4 日創建

暫無
暫無

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

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