美文网首页R语言做图R plot
ggplot2绘制柱状图+折线图

ggplot2绘制柱状图+折线图

作者: R语言数据分析指南 | 来源:发表于2021-04-01 21:50 被阅读0次

之前分享过不少绘制柱状图的案例,各种类型的都有,今天来展示一个ggplot2绘制柱状图并加上折线图的案例,依然使用TidyTuesday 2021-week-13周的数据集

加载R包

library(tidyverse)
library(tidytext)
library(ggtext)
library(lubridate)

读入数据

theme_set(theme_light())

un_votes <- read.csv("unvotes.csv",,sep=",")
issues <- read.csv("issues.csv",sep=",")
roll_calls <- read.csv("roll_calls.csv",sep=",")

数据处理

left_join函数用法参考之前的dplyr包连接数据框

roll_calls <- roll_calls %>% 
  mutate(year = year(date)) %>%
  left_join(issues)

自定义颜色

colors <-c("#E41A1C","#1E90FF","#FF8C00","#4DAF4A","#984EA3",
           "#40E0D0","#FFC0CB","#00BFFF","#FFDEAD","#90EE90",
           "#EE82EE","#00FFFF","#F0A3FF", "#0075DC", 
           "#993F00","#4C005C","#2BCE48","#FFCC99",
           "#808080","#94FFB5","#8F7C00","#9DCC00",
           "#C20088","#003380","#FFA405","#FFA8BB",
           "#426600","#FF0010","#5EF1F2","#00998F",
           "#740AFF","#990000","#FFFF00")

常规可视化

bar <- roll_calls %>%
  filter(!is.na(issue)) %>%
  count(year, issue, sort = T) %>%
  arrange(year) %>%
  ggplot(aes(x = year, y = n)) +
  geom_col(aes(fill = issue))+
  scale_fill_manual(values = colors)+labs(fill="")+
  labs(x=NULL,y=NULL)+
  theme(legend.position = "top")

保存图片

ggsave("bar.jpg", bar, height = 8, width = 12, 
       units = "in", dpi = 300)

案例(2) 柱状图+折线图

roll_calls %>%
  group_by(year) %>%
  summarize(n = n()) %>%
  ggplot(aes(x = year, y = n)) +
  geom_line()

un_plot <- roll_calls %>%
  filter(!is.na(issue)) %>%
  count(year, issue, sort = T) %>%
  arrange(year) %>%
  ggplot(aes(x = year, y = n)) +
  geom_col(aes(fill = issue)) +
  geom_line(aes(x = year, y = n),
            color = "black",data = roll_calls %>% 
              count(year)) +
  ggthemes::theme_wsj() +
  ggthemes::scale_fill_ptol()+
  theme(legend.title = element_blank())
ggsave("un_plot.jpg", 
       un_plot, 
       height = 8, width = 12, 
       units = "in", dpi = 300)

喜欢的小伙伴可以关注我的个人公众号R语言数据分析指南,持续分享更多优质资源

相关文章

网友评论

    本文标题:ggplot2绘制柱状图+折线图

    本文链接:https://www.haomeiwen.com/subject/vltghltx.html