ggplot2画折线图
“`r
# 加载R包
library(ggplot2)
library(ggthemes)
library(extrafont)
“`
“`r
# 数据加载
data1 <- read.csv("../data/copper-data-for-tutorial.csv")
str(data1)
“`
“`r
# 第一步:折线图基础
p1 <- ggplot(data = data1, aes(x = year, y = export)) +
geom_line(aes(colour = product), stat = "identity")
p1
“`
“`r
# 第二步:调整直线的宽度
p2 <- ggplot(data = data1, aes(x = year, y = export)) +
geom_line(aes(colour = product), size = 1.5, stat = "identity")
p2
“`
“`r
# 第三步:修改变量的显示
data2 <- as.data.frame(data1)
data2$product <- factor(
data2$product,
levels = c("copper","others"),
labels = c("Copper","Pulp wood, Fruit, Salmon & Others")
)
p3 <- ggplot(data = data2, aes(x = year, y = export)) +
geom_line(aes(colour = product), size = 1.5, stat = "identity") +
theme(legend.position = "bottom", legend.direction = "horizontal", legend.title = element_blank())
p3
“`
“`r
# 第四步:添加坐标轴说明和标题
p4 <- p3 +
ggtitle("Composition of Exports to China ($)") +
labs(x="Year", y="USD million") +
theme(plot.title = element_text(size = 30, face = "bold", hjust = 0.5))
p4
“`
“`r
# 第五步:调整面板颜色
colour1 <- c("#5F9EA0", "#E1B378")
p5 <- p4 + scale_color_manual(values = colour1)
p5
“`
“`r
# 第六步:主题设置
ggplot(data = data2, aes(x = year, y = export)) +
theme_bw() +
geom_line(aes(colour = product), size = 1.5, stat = "identity") +
theme(legend.position = "bottom", legend.direction = "horizontal", legend.title = element_blank()) +
scale_x_continuous(breaks=seq(2006,2014,1)) +
ggtitle("Composition of Exports to China ($)") +
labs(x="Year", y="USD million") +
theme(plot.title = element_text(size = 30, face = "bold", hjust = 0.5)) +
scale_color_manual(values = colour1)
“`
“`r
# 第七步:其它主题
ggplot(data = data2, aes(x = year, y = export)) +
theme_economist() + scale_colour_economist() +
geom_line(aes(colour = product), size = 1.5, stat = "identity") +
theme(legend.position = "bottom", legend.direction = "horizontal", legend.title = element_blank()) +
scale_x_continuous(breaks=seq(2006,2014,1)) +
ggtitle("Composition of Exports to China ($)") +
labs(x="Year", y="USD million") +
theme(plot.title = element_text(size = 30, face = "bold", hjust = 0.5)) +
scale_color_manual(values = colour1)
“`
**参考资料:**
1 http://t-redactyl.io/blog/2015/12/creating-plots-in-r-using-ggplot2-part-1-line-plots.html
您在阅读中,关于**折线图**有什么见解,请评论。
关于R语言更多内容,请阅读[**R系列文章**](http://shujuren.org/article/514.html "R系列文章")。
想加入数据人圈子,请加微信luqin360。
————