来自公众号【小明的数据分析笔记本】
原图大佬们用的管道符这边没有用上,因为是一步一步每个代码都去看了一下意思。
df_trade <- readr::read_csv("trade.csv")
library(tidyverse)
library(ggthemes)
library(cowplot)
library(ggplot2)
test<-df_trade
test<-mutate(test,trade_deficit=trade_deficit/10^9,manufacture_employment=manufacture_employment/10^5)
test<-gather(test,cat,value,-year) #改变数据框格式
p<-ggplot(test,aes(year,value,fill=cat))
p<-p+geom_col(width = 0.8)+#柱状图
geom_hline(yintercept = 0, color = "red1", size = 0.7)+ #添加横线,yintercept为y轴截距
scale_x_continuous(breaks = 1995:2016,
labels=c("1995","","","","","","","","","","2005","","","","","","","","","","","2016"))+ #改变横坐标显示的值和断点的标签
scale_y_continuous(limits = c(-380,210),
breaks=seq(-300,200,by=100))+#改变y轴刻度显示范围和刻度标记
scale_fill_manual(values = c("dodgerblue3", "firebrick4"),
labels=c("Manufacturing employment (100K)", "Trade deficit with China in goods ($B)"),
name="") #修改颜色,legend的名字和图标名字
p<-p + guides(fill = guide_legend(nrow = 2, byrow = TRUE))+ #从效果上看让两行分得更开
labs(x=NULL,y=NULL,title="",subtitle = "\n",caption = "\nVisualization by Cédric Scherer | Sources: US Census Bureau; BLS")+
theme_economist()+
theme(text = element_text(family = "serif"), #修改字体
axis.text = element_text(size = 12), #坐标轴字体大小
axis.text.y = element_text(hjust = 1), #y轴对齐方式
axis.ticks.length = unit(5, "pt"), #x轴刻度的长度
legend.text = element_text(size = 14), #图例字体大小
legend.position = "top", #图例位置
legend.justification = c(0, 1), #图例左对齐
plot.caption = element_text(color = "grey40"),#图注颜色
plot.background = element_rect(fill = "#dcf0f7"),#图表背景颜色
panel.grid.major.y = element_line(color = "grey70", size = 0.4),#y轴网格线颜色
panel.background = element_rect(fill = "#dcf0f7"))#绘图区背景颜色
p_trade <- ggdraw(p) +
draw_text("Free markets and free workers",
x = 0.01, y = 0.98,
hjust = 0, vjust = 1,
size = 20, family = "serif") +
draw_text("United States",
x = 0.01, y = 0.91,
hjust = 0,
vjust = 1,
size = 14,
family = "serif")
save_plot(filename ="p1_trade.pdf",plot=p_trade)
最后的结果~