簡體   English   中英

r filter() 問題:plotly vs ggplot

[英]r filter() issue: plotly vs ggplot

我開始使用 R(主要是情節)學習交互式數據即和基本數據分析。 我在使用 dplyr function 過濾器()時遇到問題,同時在 ZE1E1D3D40573183D6CEE21 中使用 plotly 進行繪圖。 這是使用 gapminder 數據集的示例:

library(gapminder)


# filter by year and continent
gapminder_2002_asia <- gapminder %>%
  filter(year== 2002 & continent == "Asia")
# plot gpd/capita bar chart using plotly
gapminder_2002_asia %>%
  plot_ly() %>%
  add_bars(x= ~country, y = ~gdpPercap, color = ~country)

這是結果:初始數據集中存在的所有世界國家都在 x 軸上:plotly 圖為圖像

在此處輸入圖像描述

另一方面,如果只是用 ggplot 制作 static 圖,我只有亞洲國家出現在 x 軸上:

gapminder_2002_asia %>%
  ggplot(aes(country, gdpPercap, fill = country)) +
  geom_col()

ggplot 圖

在此處輸入圖像描述

我真的不明白這是怎么發生的,因為它們都來自同一個 df..

原因是plotly采用國家變量內的所有級別,而ggplot2僅采用數據集中的可用值。 所以,為了得到同樣的結果,你可以使用這個:

library(plotly)
library(ggplot2)
#Plotly
gapminder_2002_asia %>%
  plot_ly() %>%
  add_bars(x= ~country, y = ~gdpPercap, color = ~country)

Output:

在此處輸入圖像描述

並使用ggplot2

#ggplot2
gapminder_2002_asia %>%
  ggplot(aes(country, gdpPercap, fill = country)) +
  geom_col()+
  scale_x_discrete(limits=levels(gapminder_2002_asia$country))+
  theme(axis.text.x = element_text(angle=90))

Output:

在此處輸入圖像描述

更新:為了在 plotly 中獲得相同的plotly ,您可以使用類似的東西,這將類似於您的ggplot2初始代碼進行繪圖:

#Plotly 2
gapminder_2002_asia %>%
  mutate(country=as.character(country)) %>%
  plot_ly() %>%
  add_bars(x= ~country, y = ~gdpPercap, color = ~country)

Output:

在此處輸入圖像描述

要解決的關鍵是數據集中的因素。

另一個選項可以是來自forcatsfct_drop() (非常感謝和感謝@user2554330 ):

library(forcats)
#Plotly 2
gapminder_2002_asia %>%
  mutate(country=fct_drop(country)) %>%
  plot_ly() %>%
  add_bars(x= ~country, y = ~gdpPercap, color = ~country)

Output:

在此處輸入圖像描述

很奇怪。

作為調試該代碼的替代方法,為什么不嘗試使用 ggplotly()?

例如

p <- gapminder_2002_asia %>%
ggplot(aes(country, gdpPercap, fill = country)) +
geom_col()

plotly::ggplotly(p)

我很好奇 plot 的哪個版本出現在了遠端!

暫無
暫無

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

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