The most basic drawing library in Python is matplotlib, which is the most basic Python visualization library. Generally I started with Python data visualization from matplotlib, and then started to expand vertically and horizontally.
is an advanced visualization effect library based on matplotlib. It mainly targets variable feature selection in data mining and machine learning. Seaborn can use short codes to draw and describe more Visualization of dimensional data.
Bokeh (a library used for browser-side interactive visualization to realize the interaction between analysts and data); Mapbox (processing geographical data engine for stronger visualization tool library) and so on.
This article mainly uses matplotlib for case analysis
The business may be complicated, but after splitting, we have to find our What specific issue do you want to express through graphics? For training in analytical thinking, you can learn the methods in "McKinsey Method" and "Pyramid Principle".
This is a summary on the Internet about the selection of chart types.
In Python, we can summarize it into the following four basic visual elements to display graphics:
There are relationships such as distribution, composition, comparison, connection and change trends between data. Corresponding to different relationships, select the corresponding graphics for display.
A lot of programming work in data analysis and modeling is based on data preparation: loading, cleaning, transformation and reshaping . Our visualization step also needs to organize the data, convert it into the format we need, and then apply the visualization method to complete the drawing.
The get_dummies function that converts categorical variables into 'dummy variable matrix' and limits the value of a certain column of data in df, etc.
The function will find the corresponding function in Python based on the graphics selected in the first step.
After the original graphics are drawn, we can modify the color (color), line style (linestyle), mark (maker) or other chart decorations according to needs Item title (Title), axis label (xlabel, ylabel), axis tick (set_xticks), and legend (legend), etc., make the graphics more intuitive.
The third step is based on the second step, in order to make the graphics more clear and clear. Specific parameters can be found in the charting function.
#导入包 import numpy as np import pandas as pd import matplotlib.pyplot as plt
The graphics of matplotlib are both located in Figure (canvas), and Subplot Create an image space. You cannot draw through figure. You must use add_subplot to create one or more subplots.
figsize can specify the image size.
#创建画布 fig = plt.figure() <Figure size 432x288 with 0 Axes> #创建subplot,221表示这是2行2列表格中的第1个图像。 ax1 = fig.add_subplot(221) #但现在更习惯使用以下方法创建画布和图像,2,2表示这是一个2*2的画布,可以放置4个图像 fig , axes = plt.subplots(2,2,sharex=True,sharey=True) #plt.subplot的sharex和sharey参数可以指定所有的subplot使用相同的x,y轴刻度。
Use Figure's subplots_adjust method to adjust the spacing.
subplots_adjust(left=None,bottom=None,right=None, top=None,wspace=None,hspace=None)
The plot function of matplotlib accepts a set of X and Y coordinates, and can also accept a color The string abbreviation of the line type: **'g--', which means the color is green and the line type is '--' dashed line. **It can also be specified explicitly using parameters.
Line charts can also add some markers to highlight the locations of data points. Tags can also be placed in the format string, but the tag type and line style must come after the color.
plt.plot(np.random.randn(30),color='g', linestyle='--',marker='o')
[<matplotlib.lines.Line2D at 0x8c919b0>]
plt’s xlim, xticks and xtickslabels methods control the range, scale position and tick labels of the chart respectively.
When the method is called without parameters, the current parameter value is returned; when the method is called with parameters, the parameter value is set.
plt.plot(np.random.randn(30),color='g', linestyle='--',marker='o') plt.xlim() #不带参数调用,显示当前参数; #可将xlim替换为另外两个方法试试
img
(-1.4500000000000002, 30.45)
plt.plot(np.random.randn(30),color='g', linestyle='--',marker='o') plt.xlim([0,15]) #横轴刻度变成0-15
fig = plt.figure();ax = fig.add_subplot(1,1,1) ax.plot(np.random.randn(1000).cumsum()) ticks = ax.set_xticks([0,250,500,750,1000]) #设置刻度值 labels = ax.set_xticklabels(['one','two','three','four','five']) #设置刻度标签 ax.set_title('My first Plot') #设置标题 ax.set_xlabel('Stage') #设置轴标签 Text(0.5,0,'Stage')
图例legend是另一种用于标识图标元素的重要工具。 可以在添加subplot的时候传入label参数。
fig = plt.figure(figsize=(12,5));ax = fig.add_subplot(111) ax.plot(np.random.randn(1000).cumsum(),'k',label='one') #传入label参数,定义label名称 ax.plot(np.random.randn(1000).cumsum(),'k--',label='two') ax.plot(np.random.randn(1000).cumsum(),'k.',label='three') #图形创建完后,只需要调用legend参数将label调出来即可。 ax.legend(loc='best') #要求不是很严格的话,建议使用loc=‘best’参数来让它自己选择最佳位置
除标准的图表对象之外,我们还可以自定义添加一些文字注解或者箭头。
注解可以通过text,arrow和annotate等函数进行添加。text函数可以将文本绘制在指定的x,y坐标位置,还可以进行自定义格式
plt.plot(np.random.randn(1000).cumsum()) plt.text(600,10,'test ',family='monospace',fontsize=10) #中文注释在默认环境下并不能正常显示,需要修改配置文件, # 使其支持中文字体。具体步骤请自行搜索。
利用plt.savefig可以将当前图表保存到文件。例如,要将图表保存为png文件,可以执行
文件类型是根据拓展名而定的。其他参数还有:
plt.savefig('./plot.jpg') #保存图像为plot名称的jpg格式图像 <Figure size 432x288 with 0 Axes>
matplotlib是最基础的绘图函数,也是相对较低级的工具。 组装一张图表需要单独调用各个基础组件才行。Pandas中有许多基于matplotlib的高级绘图方法,原本需要多行代码才能搞定的图表,使用pandas只需要短短几行。
我们使用的就调用了pandas中的绘图包。
import matplotlib.pyplot as plt
Series和DataFrame都有一个用于生成各类图表的plot方法。 默认情况下,他们生成的是线型图。
s = pd.Series(np.random.randn(10).cumsum(),index=np.arange(0,100,10)) s.plot() #Series对象的索引index会传给matplotlib用作绘制x轴。
<matplotlib.axes._subplots.AxesSubplot at 0xf553128>
df = pd.DataFrame(np.random.randn(10,4).cumsum(0), columns=['A','B','C','D']) df.plot() #plot会自动为不同变量改变颜色,并添加图例
<matplotlib.axes._subplots.AxesSubplot at 0xf4f9eb8>
DataFrame除了Series中的参数外,还有一些独有的选项。
在生成线型图的代码中加上kind=‘bar’或者kind=‘barh’,可以生成柱状图或水平柱状图。
fig,axes = plt.subplots(2,1) data = pd.Series(np.random.rand(10),index=list('abcdefghij')) data.plot(kind='bar',ax=axes[0],rot=0,alpha=0.3) data.plot(kind='barh',ax=axes[1],grid=True)
<matplotlib.axes._subplots.AxesSubplot at 0xfe39898>
利用value_counts图形化显示Series或者DF中各值的出现频率。
比如df.value_counts().plot(kind='bar')
Python可视化的基础语法就到这里,其他图形的绘制方法大同小异。
重点是遵循三个步骤的思路来进行思考、选择、应用。多多练习可以更加熟练。
The above is the detailed content of Three steps for Python data visualization. For more information, please follow other related articles on the PHP Chinese website!