将x和y标签添加到Pandasp

2024-04-20 14:56:42 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有以下代码,可以使用pandas绘制非常简单的图形:

import pandas as pd
values = [[1, 2], [2, 5]]
df2 = pd.DataFrame(values, columns=['Type A', 'Type B'], 
                   index=['Index 1', 'Index 2'])
df2.plot(lw=2, colormap='jet', marker='.', markersize=10, 
         title='Video streaming dropout by category')

Output

如何在保留使用特定颜色贴图的能力的同时轻松设置x和y标签?我注意到pandas数据帧的plot()包装器没有任何特定的参数。


Tags: columns代码import图形dataframepandasindexplot
3条回答

df.plot()函数返回一个matplotlib.axes.AxesSubplot对象。可以在该对象上设置标签。

In [4]: ax = df2.plot(lw=2, colormap='jet', marker='.', markersize=10, title='Video streaming dropout by category')

In [6]: ax.set_xlabel("x label")
Out[6]: <matplotlib.text.Text at 0x10e0af2d0>

In [7]: ax.set_ylabel("y label")
Out[7]: <matplotlib.text.Text at 0x10e0ba1d0>

enter image description here

或者,更简洁地说:ax.set(xlabel="x label", ylabel="y label")

或者,索引x轴标签会自动设置为索引名称(如果有)。所以df2.index.name = 'x label'也会起作用。

你可以这样做:

import matplotlib.pyplot as plt 
import pandas as pd

plt.figure()
values = [[1, 2], [2, 5]]
df2 = pd.DataFrame(values, columns=['Type A', 'Type B'], 
                   index=['Index 1', 'Index 2'])
df2.plot(lw=2, colormap='jet', marker='.', markersize=10,
         title='Video streaming dropout by category')
plt.xlabel('xlabel')
plt.ylabel('ylabel')
plt.show()

显然,你必须用你想要的字符串替换'xlabel'和'ylabel'。

如果标记数据框的列和索引,pandas将自动提供适当的标签:

import pandas as pd
values = [[1, 2], [2, 5]]
df = pd.DataFrame(values, columns=['Type A', 'Type B'], 
                  index=['Index 1', 'Index 2'])
df.columns.name = 'Type'
df.index.name = 'Index'
df.plot(lw=2, colormap='jet', marker='.', markersize=10, 
        title='Video streaming dropout by category')

enter image description here

在这种情况下,您仍然需要手动提供y标签(例如,通过plt.ylabel,如其他答案所示)。

相关问题 更多 >