Python、R绘制多彩气泡图
在工作中面对这么一个问题,使用软件实现二维气泡图,需要在每个气泡加上标签等信息。搜了一圈,关于此类的文章较少,故写篇总结,和大家一起探讨使用。
这里从网上随便找到一个数据集进行制作。
实现的气泡图为 x轴为temperature,y轴为rainfall,气泡大小为yield。
Python实现气泡图
下面展示实现的python代码。
import pandas as pd
import numpy as np
import matplotlib as mpl
from matplotlib import cm
import matplotlib.pyplot as plt
import seaborn as snsdata_1 = pd.read_csv('./product.csv')
data_1.head()#确定 product 种类个数
cate_count = np.unique(data_1['product_lable'])#根据 product 种类个数,确定色带颜色
#这里用到了列表生成式
colors = [plt.cm.tab10(i/float(len(cate_count)-1)) for i in range(len(cate_count))]#生成画布
#dpi 参数表示清晰度
fig = plt.figure(figsize=(10,8), dpi=120)
#开始循环作图
for i, product_lable in enumerate(cate_count):plt.scatter('temperature','rainfall', data=data_1.loc[data_1.product_lable == product_lable,:]#根据 yield 确定气泡大小。, s = 'yield'#使用颜色,由于参数 c 接受一维数组,所以需要转化,否则会出警告, c= np.array(colors[i]).reshape(1,-1)#直接使用循环的 product 遍历的值作为本次循环的标签, label=str(product_lable)#将散点边缘颜色改成本次循环的颜色,否则默认是黑边, edgecolors = np.array(colors[i]).reshape(1,-1)#调整散点透明度, alpha = 0.65)
plt.legend(markerscale=0.2,bbox_to_anchor=(1.05, 0), loc=3, borderaxespad=0)
plt.xlabel('temperature')
plt.ylabel('rainfall')
plt.show()
即可实现下述图形。自己实现的时候只需修改自己的数据集即可。
R实现气泡图
下面展示实现的R语言代码。
data1 = read.csv('./product.csv')
# 软件包须自己install.packages
library(ggrepel)
library(hrbrthemes)
library(viridis)
library(ggridges)
library(tidyverse)ggplot(data1,aes(x=temperature, y=rainfall, size=yield, fill=product_lable)) + geom_point(alpha=0.5, shape=21, color="black") + scale_size(range = c(10,24), name="yield") + geom_text_repel(label = product_lable,size=5)+ scale_fill_viridis(discrete=TRUE, guide=FALSE, option="A") + theme_ipsum() + theme(legend.position="bottom") + ylab("rainfall") + xlab("temperature") + theme(legend.position = "none")
即可实现下述图形。自己实现的时候只需修改自己的数据集即可。