其他
数据呈现丨小白学数据可视化:一个ggplot2画图完整实例
The following article is from R语言 Author 王路情
加载ggplot2包和数据集
library(ggplot2)
data(mpg)
左右滑动查看更多
确定画图数据集和展示的变量或者变量集
ggplot(data = mpg, mapping = aes(x = displ, y = hwy))
Q
图形为什么是空的?
确定所要展示的几何图形
ggplot2包画图的原理采用分层的思想来作图和完善图。我们选用两个连续变量displ和hwy,想了解它们之间的关系,我们采用散点图。ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) +
geom_point()
左右滑动查看更多
library(tidyverse)
filter(mpg, hwy <= median(mpg$hwy)) %>%
ggplot(mapping = aes(x = displ, y = hwy)) +
geom_point()
左右滑动查看更多
对点进行修饰
ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) +
geom_point(
color = 'cornflowerblue',
size = 3,
alpha = .5
)
左右滑动查看更多
添加拟合曲线
ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) +
geom_point(
color = 'cornflowerblue',
size = 3,
alpha = .5
) +
geom_smooth(method = 'lm')
左右滑动查看更多
同一幅图中分组展示
ggplot(data = mpg, mapping = aes(x = displ, y = hwy, color = drv)) +
geom_point(
size = 3,
alpha = .5
) +
geom_smooth(
method = 'lm',
se = FALSE,
size = 1.5
)
左右滑动查看更多
Q
如下这段代码运行后,会是什么结果?
ggplot(data = mpg, mapping = aes(x = displ, y = hwy, color = drv)) +
geom_point(
color = 'cornflowerblue',
size = 3,
alpha = .5
) +
geom_smooth(
method = 'lm',
se = FALSE,
size = 1.5
)
设置scale
mpg %>% select(displ, hwy, drv) %>%
ggplot(mapping = aes(x = displ, y = hwy, color = drv)) +
geom_point(size = 3,
alpha = .5) +
geom_smooth(
method = 'lm',
se = FALSE,
size = 1.5) +
scale_x_continuous(breaks = seq(1.6, 8, 2)) +
scale_y_continuous(breaks = seq(12, 45, 5))
左右滑动查看更多
添加facet
mpg %>% select(displ, hwy, drv, model) %>%
ggplot(mapping = aes(x = displ, y = hwy, color = drv)) +
geom_point(size = 3,
alpha = .5) +
geom_smooth(
method = 'lm',
se = FALSE,
size = 1.5) +
scale_x_continuous(breaks = seq(1.6, 8, 2)) +
scale_y_continuous(breaks = seq(12, 45, 5)) +
facet_wrap(~model)
添加labels
mpg %>% select(displ, hwy, drv, model) %>%
ggplot(mapping = aes(x = displ, y = hwy, color = drv)) +
geom_point(size = 3,
alpha = .5) +
geom_smooth(
method = 'lm',
se = FALSE,
size = 1.5) +
scale_x_continuous(breaks = seq(1.6, 8, 2)) +
scale_y_continuous(breaks = seq(12, 45, 5)) +
facet_wrap(~model) +
labs(title = "displ和hwy的关系图",
caption = "source: http://shujuren.org/",
x = '变量displ',
y = '变量hwy',
color = "Drv_type")
左右滑动查看更多
选择合适的主题
mpg %>% select(displ, hwy, drv, model) %>%
ggplot(mapping = aes(x = displ, y = hwy, color = drv)) +
geom_point(size = 3,
alpha = .5) +
geom_smooth(
method = 'lm',
se = FALSE,
size = 1.5) +
scale_x_continuous(breaks = seq(1.6, 8, 2)) +
scale_y_continuous(breaks = seq(12, 45, 5)) +
facet_wrap(~model) +
labs(title = "displ和hwy的关系图",
caption = "source: http://shujuren.org/",
x = '变量displ',
y = '变量hwy',
color = "Drv_type") +
theme_minimal()
左右滑动查看更多
总结
►一周热文
工具&方法丨划重点 !经济学专业学Python需要学哪些内容?——数据分析处理必知必会的知识点
数据Seminar
这里是大数据、分析技术与学术研究的三叉路口
欢迎扫描👇二维码添加关注