一、绘制散点图
二、绘制边界气泡图
一、绘制散点图实现功能:
python绘制散点图,展现两个变量间的关系,当数据包含多组时,使用不同颜色和形状区分。
实现代码:
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings(action='once')
plt.style.use('seaborn-whitegrid')
sns.set_style("whitegrid")
print(mpl.__version__)
print(sns.__version__)
def draw_scatter(file):
# Import dataset
midwest = pd.read_csv(file)
# Prepare Data
# Create as many colors as there are unique midwest['category']
categories = np.unique(midwest['category'])
colors = [plt.cm.Set1(i / float(len(categories) - 1)) for i in range(len(categories))]
# Draw Plot for Each Category
plt.figure(figsize=(10, 6), dpi=100, facecolor='w', edgecolor='k')
for i, category in enumerate(categories):
plt.scatter('area', 'poptotal', data=midwest.loc[midwest.category == category, :],s=20,c=colors[i],label=str(category))
# Decorations
plt.gca().set(xlim=(0.0, 0.1), ylim=(0, 90000),)
plt.xticks(fontsize=10)
plt.yticks(fontsize=10)
plt.xlabel('Area', fontdict={'fontsize': 10})
plt.ylabel('Population', fontdict={'fontsize': 10})
plt.title("Scatterplot of Midwest Area vs Population", fontsize=12)
plt.legend(fontsize=10)
plt.show()
draw_scatter("F:\数据杂坛\datasets\midwest_filter.csv")
实现效果:
二、绘制边界气泡图实现功能:
气泡图是散点图中的一种类型,可以展现三个数值变量之间的关系,之前的文章介绍过一般的散点图都是反映两个数值型变量的关系,所以如果还想通过散点图添加第三个数值型变量的信息,一般可以使用气泡图。气泡图的实质就是通过第三个数值型变量控制每个散点的大小,点越大,代表的第三维数值越高,反之亦然。而边界气泡图则是在气泡图添加第四个类别型变量的信息,将一些重要的点选出来并连接。
实现代码:
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
from scipy.spatial import ConvexHull
warnings.filterwarnings(action='once')
plt.style.use('seaborn-whitegrid')
sns.set_style("whitegrid")
print(mpl.__version__)
print(sns.__version__)
def draw_scatter(file):
# Step 1: Prepare Data
midwest = pd.read_csv(file)
# As many colors as there are unique midwest['category']
categories = np.unique(midwest['category'])
colors = [plt.cm.Set1(i / float(len(categories) - 1)) for i in range(len(categories))]
# Step 2: Draw Scatterplot with unique color for each category
fig = plt.figure(figsize=(10, 6), dpi=80, facecolor='w', edgecolor='k')
for i, category in enumerate(categories):
plt.scatter('area','poptotal',data=midwest.loc[midwest.category == category, :],s='dot_size',c=colors[i],label=str(category),edgecolors='black',linewidths=.5)
# Step 3: Encircling
# https://stackoverflow.com/questions/44575681/how-do-i-encircle-different-data-sets-in-scatter-plot
def encircle(x, y, ax=None, **kw): # 定义encircle函数,圈出重点关注的点
if not ax: ax = plt.gca()
p = np.c_[x, y]
hull = ConvexHull(p)
poly = plt.Polygon(p[hull.vertices, :], **kw)
ax.add_patch(poly)
# Select data to be encircled
midwest_encircle_data1 = midwest.loc[midwest.state == 'IN', :]
encircle(midwest_encircle_data1.area,midwest_encircle_data1.poptotal,ec="pink",fc="#74C476",alpha=0.3)
encircle(midwest_encircle_data1.area,midwest_encircle_data1.poptotal,ec="g",fc="none",linewidth=1.5)
midwest_encircle_data6 = midwest.loc[midwest.state == 'WI', :]
encircle(midwest_encircle_data6.area,midwest_encircle_data6.poptotal,ec="pink",fc="black",alpha=0.3)
encircle(midwest_encircle_data6.area,midwest_encircle_data6.poptotal,ec="black",fc="none",linewidth=1.5,linestyle='--')
# Step 4: Decorations
plt.gca().set(xlim=(0.0, 0.1),ylim=(0, 90000),)
plt.xticks(fontsize=12)
plt.yticks(fontsize=12)
plt.xlabel('Area', fontdict={'fontsize': 14})
plt.ylabel('Population', fontdict={'fontsize': 14})
plt.title("Bubble Plot with Encircling", fontsize=14)
plt.legend(fontsize=10)
plt.show()
draw_scatter("F:\数据杂坛\datasets\midwest_filter.csv")
实现效果:
到此这篇关于python可视化分析绘制散点图和边界气泡图的文章就介绍到这了,更多相关python绘制内容请搜索软件开发网以前的文章或继续浏览下面的相关文章希望大家以后多多支持软件开发网!