好色之徒数据-R语言-图表-决策-Linux-Python

2019-04-25用ggplot2绘制散点图

2019-04-25  本文已影响15人  iColors

文章改编自https://michaeltoth.me/a-detailed-guide-to-the-ggplot-scatter-plot-in-r.html#a-detailed-guide-to-the-ggplot-scatter-plot-in-r

散点图是最常见的统计绘图之一,作图当然要第一传递有用的、有意义的信息,然后是做的酷炫。这样给老板汇报,还是做学术演讲,再到要人命的SCI文章的发表,都比较重要。

这就是一个好的散点图例子,Scatter Plot of Adam Sandler Movies from FiveThirtyEight, Adam Sandler 的电影被分成了三个类别,用不同的颜色进行显示。

image.png

另外一个比较喜欢的例子,The Famous Gapminder Scatter Plot of Life Expectancy vs. Income by Country,有力的展现了寿命预期和收入间的关系,有趣的是中国和印度是两个中心点,以人口数作为点大小的标尺进行了绘图,从贫穷到富裕国家进行了分类。


image.png

下面用ggplot2绘制一下简单的散点图,用它自带的mtcars数据包。

(1)先看一下数据,包含11列。

head(mtcars,n=10)
                   mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag     21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
Duster 360        14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
Merc 240D         24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
Merc 230          22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
Merc 280          19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4

(2)用ggplot图绘制简单散点图

library(ggplot2)
ggplot(mtcars) + geom_point(aes(x = wt, y = mpg))
image.png

(3)改点的颜色为蓝色

ggplot(mtcars) + geom_point(aes(x = wt, y = mpg), color = 'blue')
image.png

(4)以am区分各个点的颜色

mtcars$am <- factor(mtcars$am)#先把am改成因子型
ggplot(mtcars) +  geom_point(aes(x = wt, y = mpg, color = am))
image.png

如果你不改am为因子型,am是数值向量,绘制的散点的深浅表示am的数值大小,这样就不能代表am的意义,因为它是代表的自动还是手动挡的车,是一个2分类变量,不是数值变量。错误的绘图如下:


image.png

(5)根据am,以形状区分。

ggplot(mtcars) + geom_point(aes(x = wt, y = mpg, shape = am))
image.png

(6)根据cyl的数值大小,区分各个散点。

ggplot(mtcars) +  geom_point(aes(x = wt, y = mpg, size = cyl))
image.png

(7)改变点的透明度。

ggplot(mtcars) +  geom_point(aes(x = wt, y = mpg, alpha = cyl))
image.png

(8)也可以设置透明度为固定值。

ggplot(mtcars) +  geom_point(aes(x = wt, y = mpg, size = cyl), alpha = 0.3)
image.png

(9)点的形状也可以根据需要更换。

ggplot(mtcars) +   geom_point(aes(x = wt, y = mpg), shape = 18)
image.png

(10)最后,按照一开始的例2图,仿制一张散点图。是不是改一改就能发表了,哈哈哈!!!

mtcars$cyl <- factor(mtcars$cyl)
ggplot(mtcars) +  geom_point(aes(x = wt, y = mpg, color = cyl,size = cyl))+theme_bw()
image.png
上一篇下一篇

猜你喜欢

热点阅读