小言_互联网的博客

R语言绘制气泡图

209人阅读  评论(0)

今天跟大家分享的是R绘制气泡图的代码。

数据长这样:
mtcars.csv

1.先使用ggplot2包绘制散点图(之前有分享过散点图绘制代码);

library(ggplot2)

ggplot(mtcars, aes(wt, mpg))+
  geom_point(aes(colour = factor(cyl)))


2.接着来绘制气泡图;

df <- data.frame(year=rep(c(2017,2018),3),
                 product=rep(c('ProductA','ProductB','ProductC'),2),
                 ratio=runif(6, min = 0, max = 1))

df <- df[order(df$year),]
df <- within(df,{
   bubblesize<- sqrt(df$ratio*10/pi)})
df$product <- factor(df$product,levels=unique(df$product),ordered=TRUE)
ratio.mean <- mean(df$ratio)
y.min <- min(df$ratio)
mytheme <- theme_minimal()+
  theme(
    panel.grid.major.y=element_blank(),
    panel.grid.minor.y=element_blank(),
    axis.text.x = element_text(angle = 45, hjust = 1),
    plot.title=element_text(hjust =0.5),
    axis.line.y=element_line(linetype=1,color='grey'),
    axis.line.x=element_line(linetype=1,color='grey'),
    axis.ticks = element_line(linetype=2,color='grey'),
    panel.grid=element_line(linetype=2,color='grey'),
    legend.background = element_rect(fill="gray90", size=0,color='white'),
    legend.text=element_text(face="bold",size=8),
    legend.title=element_text(face="bold",size=8),
    axis.text=element_text(face="bold",size=8)
  )

ggplot(data=df, mapping=aes(x=product,y=ratio,color=factor(year)))+
  geom_point(stat= "identity",aes(size=bubblesize),alpha=0.7,show.legend = TRUE)+ 
  guides(color=guide_legend(title="Year"))+
  scale_size(range = c(1, 30),guide=FALSE)+
  scale_color_manual(values=c("#666666","#FF0016"))+
  scale_y_continuous(labels = scales::percent,limits=c(y.min,1))+
  labs(x='Product',y='Increase ratio',title='Product increase ratio')+
  geom_text(aes(y=ratio,label=scales::percent(ratio),hjust=0.5), size=3,color="black",position = position_dodge(width=0.00),check_overlap = FALSE) +
  mytheme+
  geom_hline(yintercept = ratio.mean,linetype='dashed')+
  annotate(geom='text',x=0,y=ratio.mean,label=scales::percent(ratio.mean),hjust=-0.4,vjust=-0.5);
#scale_size()图层用于指定bubble的大小,annotate()函数用于为水平线添加文本说明


3.借鉴了其他大神另一种绘制方形气泡图的代码;

library(ggplot2)
library(RColorBrewer)
library(ggrepel)
mydata <- read.csv(file.choose(),row.names = 1) #选择mtcars数据集

ggplot(mydata, aes(wt,mpg))+
  geom_point(aes(size=disp,fill=disp),shape=22,colour="black",alpha=0.8)+
  scale_fill_gradient2(low=brewer.pal(7,"Set1")[2],high=brewer.pal(7,"Set1")[1],
                       midpoint = mean(mydata$disp))+
  scale_size_area(max_size=12)+
  guides(fill = guide_legend((title="Value")),
         size =  guide_legend((title="Value")))+
  theme(
    text=element_text(size=15,color="black"),
    plot.title=element_text(size=15,family="myfont",face="bold.italic",color="black")#,
    #legend.position=c(0.9,0.05)
  )


觉得实用可以收藏起来,需要数据的小伙伴可关注“作图帮”公众号进群获取。


转载:https://blog.csdn.net/weifanbio/article/details/116518394
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场