如何在折叠条形图（Dplyr）上叠加折线图？

问题描述投票：0回答：1

``````ID   Year   Party  Change
1    2010   Labour  NA
1    2011   Labour  No Change
1    2012   Con     Change
1    2013   Con     No Change
2    2010   Con     No Change
2    2011   Con     No Change
2    2012   Con     No Change
2    2013   Con     No Change
... etc.
``````

``````library(dplyr)
library(ggplot2)

df %>%
group_by(Change) %>%
filter(Year != 2010) %>%
ggplot(aes(fill = Change, y = ID, x= Year)) +
geom_bar(stat="identity", position = "fill") +
xlab("Year") +
ylab("% of Sample")
``````

https://imgur.com/lhCoXaR

``````
ggplot(df, aes(fill = PolParty, y = pidp, x = wave)) +
geom_bar(stat="identity", position = "fill") +
xlab("Year") +
ylab("% of Sample") +

``````

https://imgur.com/0qbIL5h

r ggplot2 dplyr stacked-chart linegraph
1个回答
1

``````library(dplyr)
library(ggplot2)

data <- "ID   Year   Party  Changed_seats
1    2010   Labour  NA
1    2011   Labour  No_Change
1    2012   Con     Change
1    2013   Con     No_Change
2    2010   Con     No_Change
2    2011   Con     No_Change
2    2012   Con     No_Change
2    2013   Con     No_Change
3    2014   Con     No_Change
3    2015   Con     Change
3    2016   Con     Change
3    2017   Con     No_Change
4    2014   Con     No_Change
4    2015   Con     Change
4    2016   Con     Change
4    2017   Con     No_Change"

seat_changes_df <- df %>%
select(Year, Changed_seats) %>%
mutate(Year = as.factor(Year)) %>%
group_by(Year) %>%
mutate(Prop_change = sum(Changed_seats == "Change")/n())

ggplot() +
geom_line(data = seat_changes_df, aes(x = Year, y = Prop_change), group = 1) +
scale_y_continuous(labels = scales::percent) +
xlab("Year") +
ylab("Seats changed")
#> Warning: Removed 2 rows containing missing values (geom_path).
``````