赞
踩
目录
Python画图常用代码总结,现拿现用!Python画图常用代码总结,现拿现用!
大家好,今天分享给大家20个Matplotlib图的汇总,在数据分析与可视化中非常有用,大家可以收藏下来慢慢练手。
Scatteplot是用于研究两个变量之间关系的经典和基本图。如果数据中有多个组,则可能需要以不同颜色可视化每个组。在Matplotlib,你可以方便地使用。
-
- # Import dataset
- midwest = pd.read_csv("https://raw.githubusercontent.com/selva86/datasets/master/midwest_filter.csv")
-
- # Prepare Data
- # Create as many colors as there are unique midwest['category']
- categories = np.unique(midwest['category'])
- colors = [plt.cm.tab10(i/float(len(categories)-1)) for i in range(len(categories))]
-
- # Draw Plot for Each Category
- plt.figure(figsize=(16, 10), dpi= 80, 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),
- xlabel='Area', ylabel='Population')
-
- plt.xticks(fontsize=12); plt.yticks(fontsize=12)
- plt.title("Scatterplot of Midwest Area vs Population", fontsize=22)
- plt.legend(fontsize=12)
- plt.show()
展示图:
有时,你希望在边界内显示一组点以强调其重要性。在此示例中,你将从应该被环绕的数据帧中获取记录,并将其传递给下面的代码中描述的记录。encircle()
- from matplotlib import patches
- from scipy.spatial import ConvexHull
- import warnings; warnings.simplefilter('ignore')
- sns.set_style("white")
-
- # Step 1: Prepare Data
- midwest = pd.read_csv("https://raw.githubusercontent.com/selva86/datasets/master/midwest_filter.csv")
-
- # As many colors as there are unique midwest['category']
- categories = np.unique(midwest['category'])
- colors = [plt.cm.tab10(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=(16, 10), 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):
- 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_data = midwest.loc[midwest.state=='IN', :]
-
- # Draw polygon surrounding verti
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。