美文网首页大数据
【数据可视化】用R一秒绘制南丁格尔玫瑰图

【数据可视化】用R一秒绘制南丁格尔玫瑰图

作者: 枫璃 | 来源:发表于2020-04-09 17:00 被阅读0次

上一章介绍了用Python制作南丁格尔玫瑰图(https://www.jianshu.com/p/260d23bddbbc),这里发现用R更方便,堪称一秒变玫瑰!

下面我们来看看怎么用R来画南丁格尔玫瑰图:

1、加载所需的包

library(ggplot2)

2、读入数据

疫情地图.csv

a1 = read.csv("E:\\hill2020\\Python相关\\疫情地图.csv",sep=',',header=TRUE)

#取前20条数据

a <- a1[1:20,]

3、画柱形图

p <- ggplot(a,aes(x=continent, y=num, fill=continent))+ geom_bar(stat="identity", color="black")

4、1秒钟变玫瑰图,使用极坐标,被像折扇子一样将柱形图折叠为玫瑰图

p +  coord_polar()

5、图片调整:去掉背景&中间留空:

ylim函数用于调整y坐标轴的最大最小值。

p +  coord_polar() + theme_bw() + ylim(-50000,200000)

6、如果想按照数值从高到小排序的话,调整一下ggplot的参数即可:

修改处是reorder函数:

 p <- ggplot(a,aes(x=reorder(continent,num), y=num, fill=continent))+ geom_bar(stat="identity", color="black")

p +  coord_polar() + theme_bw() + ylim(-20000,170000)

7、稍微调整下图片形式,去除坐标轴、网格线、设置标签等,使图表更清晰,并在中心加文字等:

a$label <- paste(a$continent,a$num) 

p <- ggplot(a,aes(x=reorder(continent,num), y=num, fill=continent,label=label))+ geom_bar(stat="identity", color="black")

p +  coord_polar() + theme_bw() + ylim(-20000,170000) +

theme(

        panel.grid = element_blank(),

        panel.border= element_blank(),

        axis.text.y = element_blank(),

axis.text.x = element_blank(),

        axis.ticks = element_blank(),

        axis.title = element_blank(),

plot.margin = unit(c(0,-20,-20,-20),"cm")) +

annotate("text",x=0, y=-20000, label="累计确诊\ntop20国家", fontface="bold", colour="steelblue", size=6) +

geom_text(aes(label = label),size=3, vjust = "left", hjust = "outward",  color = "dark blue", fontface="bold" ) +

guides(fill=F) #不显示图例

1)添加标签的函数是geom_text(),函数中各参数的含义:

        ·size:设置字体大小

        ·fontface:可设置粗体或斜体,“plain”默认普通值, “bold” 粗体、 “italic”斜体。

        ·vjust:调整纵向位置  ["bottom","middle","top","inward(文字对齐到主画面)","outward"]

        ·hjust:调整横向位置  ["left","center","right","inward(文字对齐到主画面)","outward"]

2)plot.margin用于调整边界参数,通过数值的调整可以改变图片大小。

最终生成的玫瑰图:

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

更多数据相关文章,欢迎关注公众号“大数据会”,一起学习交流,留言可以获取相关数据哦!

相关文章

网友评论

    本文标题:【数据可视化】用R一秒绘制南丁格尔玫瑰图

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