Python Data Science 简明教程

Python - Chart Properties

Python 具有出色的数据可视化库。“ Pandas ”、 numpy ” 和 “ matplotlib ” 的组合可以帮助创建几乎所有类型的可视化图表。在本章中,我们将开始了解一些简单的图表和图表的不同属性。

Python has excellent libraries for data visualization. A combination of Pandas, numpy and matplotlib can help in creating in nearly all types of visualizations charts. In this chapter we will get started with looking at some simple chart and the various properties of the chart.

Creating a Chart

我们使用 numpy 库创建要映射以创建图表的所需数字,并使用 matplotlib 中的 pyplot 方法绘制实际图表。

We use numpy library to create the required numbers to be mapped for creating the chart and the pyplot method in matplotlib to draws the actual chart.

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0,10)
y = x ^ 2
#Simple Plot
plt.plot(x,y)

它的 output 如下所示 −

Its output is as follows −

chartprop1

Labling the Axes

我们可以使用库中适当的方法对轴和图表的标题应用标签,如下所示。

We can apply labels to the axes as well as a title for the chart using appropriate methods from the library as shown below.

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0,10)
y = x ^ 2
#Labeling the Axes and Title
plt.title("Graph Drawing")
plt.xlabel("Time")
plt.ylabel("Distance")
#Simple Plot
plt.plot(x,y)

它的 output 如下所示 −

Its output is as follows −

chartprop2

Formatting Line type and Colour

可以使用库中适当的方法来指定图表中线的样式和颜色,如下所示。

The style as well as colour for the line in the chart can be specified using appropriate methods from the library as shown below.

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0,10)
y = x ^ 2
#Labeling the Axes and Title
plt.title("Graph Drawing")
plt.xlabel("Time")
plt.ylabel("Distance")

# Formatting the line colors
plt.plot(x,y,'r')

# Formatting the line type
plt.plot(x,y,'>')

它的 output 如下所示 −

Its output is as follows −

chartprop3

Saving the Chart File

可以使用库中提供的方法将图表保存为不同的图像文件格式,如下所示。

The chart can be saved in different image file formats using appropriate methods from the library as shown below.

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0,10)
y = x ^ 2
#Labeling the Axes and Title
plt.title("Graph Drawing")
plt.xlabel("Time")
plt.ylabel("Distance")

# Formatting the line colors
plt.plot(x,y,'r')

# Formatting the line type
plt.plot(x,y,'>')

# save in pdf formats
plt.savefig('timevsdist.pdf', format='pdf')

上述代码在 python 环境的默认路径中创建 pdf 文件。

The above code creates the pdf file in the default path of the python environment.