pandas绘图显示值标签
Pandas plotting methods provide an easy way to plot pandas objects. Often though, you’d like to add axis labels, which involves understanding the intricacies of Matplotlib syntax. Thankfully, there’s a way to do this entirely using pandas.
熊猫绘制方法提供了一种绘制熊猫对象的简便方法。 但是,通常您想添加轴标签,这涉及了解Matplotlib语法的复杂性。 幸运的是,有一种方法可以完全使用熊猫来做到这一点。
Let’s start by importing the required libraries:
首先导入所需的库:
python">import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline
python">import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline
Next, we’ll create a test dataframe, with a column of names and corresponding test scores:
接下来,我们将创建一个测试数据框,其中包含一列名称和相应的测试分数:
name | 名称 | score | 得分 | ||
---|---|---|---|---|---|
0 | 0 | Joe | 乔 | 42 | 42 |
1 | 1个 | Sally | 莎莉 | 37 | 37 |
2 | 2 | Ananya | 阿南亚 | 98 | 98 |
Plotting this dataframe is simple with the pandas methods. We can just use the DataFrame.plot.bar()
method to produce a bar plot in two lines.
使用pandas方法绘制此数据框很简单。 我们可以仅使用DataFrame.plot.bar()
方法在两行中生成条形图。
python">df.plot.bar() plt.show()
python">df.plot.bar() plt.show()
This gives us instant results, but it’s not easy to interpret this plot, because we can’t see which scores belong to which name. If you look closely, you might notice the currently x-axis labels are 0
, 1
, and 2
. These actually correspond with the dataframe index.
这给了我们即时的结果,但是要解释这个图并不容易,因为我们看不到哪个分数属于哪个名字。 如果你仔细观察,你可能会注意到当前x轴标签是0
, 1
,和2
。 这些实际上与数据帧索引相对应。
By setting the index of the dataframe to our names using the set_index()
method, we can easily produce axis labels and improve our plot. We’ll use drop=True
which will remove the column, and inplace=True
instead of having to assign the variable back to itself or to a new variable name.
通过使用set_index()
方法将数据set_index()
的索引设置为我们的名称,我们可以轻松生成轴标签并改善图。 我们将使用drop=True
删除列,并使用inplace=True
而不是将变量分配回自身或新的变量名称。
score | 得分 | ||
---|---|---|---|
name | 名称 | ||
Joe | 乔 | 33 | 33 |
Sally | 莎莉 | 95 | 95 |
Ananya | 阿南亚 | 36 | 36 |
Now, let’s plot again and see our results:
现在,让我们再次绘图并查看结果:
python">df.plot.bar() plt.show()
python">df.plot.bar() plt.show()
Instantly, our plot is better looking, and clearly communicates the data!
立刻,我们的绘图看起来更好,并且清楚地传达了数据!
翻译自: https://www.pybloggers.com/2017/12/adding-axis-labels-to-plots-with-pandas/
pandas绘图显示值标签