Python Data Science 简明教程
Python - Chart Styling
使用用于绘图的库中的一些适当方法,可以进一步设置 Python 中创建的图表样式。在本课中,我们将看到注释、图例和图表背景的实现。我们将继续使用上一章中的代码并对其进行修改,以将这些样式添加到图表中。
The charts created in python can have further styling by using some appropriate methods from the libraries used for charting. In this lesson we will see the implementation of Annotation, legends and chart background. We will continue to use the code from the last chapter and modify it to add these styles to the chart.
Adding Annotations
很多时候,我们需要通过突出图表中的特定位置来注释图表。在下面的示例中,我们通过在这些点添加注释来指示图表中值的急剧变化。
Many times, we need to annotate the chart by highlighting the specific locations of the chart. In the below example we indicate the sharp change in values in the chart by adding annotations at those points.
import numpy as np
from matplotlib import pyplot as plt
x = np.arange(0,10)
y = x ^ 2
z = x ^ 3
t = x ^ 4
# Labeling the Axes and Title
plt.title("Graph Drawing")
plt.xlabel("Time")
plt.ylabel("Distance")
plt.plot(x,y)
#Annotate
plt.annotate(xy=[2,1], s='Second Entry')
plt.annotate(xy=[4,6], s='Third Entry')
它的 output 如下所示 −
Its output is as follows −
Adding Legends
我们有时需要一个绘制多条线的图表。使用图例表示与每条线相关的含义。在下面的图表中,我们有 3 条线,它们有适当的图例。
We sometimes need a chart with multiple lines being plotted. Use of legend represents the meaning associated with each line. In the below chart we have 3 lines with appropriate legends.
import numpy as np
from matplotlib import pyplot as plt
x = np.arange(0,10)
y = x ^ 2
z = x ^ 3
t = x ^ 4
# Labeling the Axes and Title
plt.title("Graph Drawing")
plt.xlabel("Time")
plt.ylabel("Distance")
plt.plot(x,y)
#Annotate
plt.annotate(xy=[2,1], s='Second Entry')
plt.annotate(xy=[4,6], s='Third Entry')
# Adding Legends
plt.plot(x,z)
plt.plot(x,t)
plt.legend(['Race1', 'Race2','Race3'], loc=4)
它的 output 如下所示 −
Its output is as follows −
Chart presentation Style
我们可以使用样式包中的不同方法来修改图表的显示样式。
We can modify the presentation style of the chart by using different methods from the style package.
import numpy as np
from matplotlib import pyplot as plt
x = np.arange(0,10)
y = x ^ 2
z = x ^ 3
t = x ^ 4
# Labeling the Axes and Title
plt.title("Graph Drawing")
plt.xlabel("Time")
plt.ylabel("Distance")
plt.plot(x,y)
#Annotate
plt.annotate(xy=[2,1], s='Second Entry')
plt.annotate(xy=[4,6], s='Third Entry')
# Adding Legends
plt.plot(x,z)
plt.plot(x,t)
plt.legend(['Race1', 'Race2','Race3'], loc=4)
#Style the background
plt.style.use('fast')
plt.plot(x,z)
它的 output 如下所示 −
Its output is as follows −