【问题标题】:Add x and y labels to a pandas plot将 x 和 y 标签添加到熊猫图
【发布时间】:2014-02-24 13:49:46
【问题描述】:

假设我有以下代码,它使用 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')

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

【问题讨论】:

标签: python pandas dataframe matplotlib


【解决方案1】:

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

ax = df2.plot(lw=2, colormap='jet', marker='.', markersize=10, title='Video streaming dropout by category')
ax.set_xlabel("x label")
ax.set_ylabel("y label")

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

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

【讨论】:

  • set_xlabel 或 set_ylabel 不适用于 pandas 0.25.1。但是, ax.set(xlabel="x label", ylabel="y label") 可以。
【解决方案2】:

你可以这样做:

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”替换为您想要的字符串。

【讨论】:

  • 另外请注意,您必须在df.plot() 之后调用plt.xlabel() 等,而不是之前,因为否则您会得到两个图 - 调用将修改“先前”图。 plt.title() 也是如此。
【解决方案3】:

如果您为 DataFrame 的列和索引添加标签,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')

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

【讨论】:

  • 目前,“从 DataFrame 自动供应”不起作用。我刚刚尝试过(pandas 版本 0.16.0,matplotlib 1.4.3)并且绘图正确生成,但轴上没有标签。
  • @szeitlin 你能在 pandas github 页面上提交错误报告吗? github.com/pydata/pandas/issues
  • 你知道吗,今天至少 xlabel 正在工作。也许我昨​​天使用的数据框有些奇怪(?)。如果我能复制它,我会归档它!
【解决方案4】:

可以将两个标签与axis.set 函数一起设置。查找示例:

import pandas as pd
import matplotlib.pyplot as plt
values = [[1,2], [2,5]]
df2 = pd.DataFrame(values, columns=['Type A', 'Type B'], index=['Index 1','Index 2'])
ax = df2.plot(lw=2,colormap='jet',marker='.',markersize=10,title='Video streaming dropout by category')
# set labels for both axes
ax.set(xlabel='x axis', ylabel='y axis')
plt.show()

【讨论】:

  • 我喜欢.set(xlabel='x axis', ylabel='y axis') 解决方案,因为它让我可以将所有内容放在一行中,这与 set_xlabel 和 set_ylabel 绘图方法不同。我想知道为什么它们(包括 set 方法,顺便说一句)不返回绘图对象或至少从它继承的东西。
【解决方案5】:

对于您使用pandas.DataFrame.hist的情况:

plt = df.Column_A.hist(bins=10)

请注意,您会得到一个 ARRAY 的图,而不是一个图。因此,要设置 x 标签,您需要执行以下操作

plt[0][0].set_xlabel("column A")

【讨论】:

    【解决方案6】:

    怎么样...

    import pandas as pd
    import matplotlib.pyplot as plt
    
    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')
        .set(xlabel='x axis',
             ylabel='y axis'))
    
    plt.show()
    

    【讨论】:

      【解决方案7】:

      在 Pandas 版本 1.10 中,您可以在方法 plot 中使用参数 xlabelylabel

      df.plot(xlabel='X Label', ylabel='Y Label', title='Plot Title')
      

      【讨论】:

        【解决方案8】:

        pandas 使用matplotlib 绘制基本数据框图。因此,如果您使用 pandas 进行基本绘图,您可以使用 matplotlib 进行绘图自定义。但是,我在这里提出了一种使用seaborn 的替代方法,它允许对绘图进行更多自定义,而不是进入matplotlib 的基本级别。

        工作代码:

        import pandas as pd
        import seaborn as sns
        values = [[1, 2], [2, 5]]
        df2 = pd.DataFrame(values, columns=['Type A', 'Type B'], 
                           index=['Index 1', 'Index 2'])
        ax= sns.lineplot(data=df2, markers= True)
        ax.set(xlabel='xlabel', ylabel='ylabel', title='Video streaming dropout by category') 
        

        【讨论】:

        • 这个特定的用例似乎不是使用 seaborn 的理由。如the top-voted answer 所示,您可以直接在从DataFrame.plot 返回的值上调用set(这与您在此处显示的代码非常相似,只是没有添加依赖项)。
        猜你喜欢
        • 2021-03-10
        • 2020-11-05
        • 1970-01-01
        • 2019-04-27
        • 1970-01-01
        • 2016-04-10
        • 2020-04-17
        • 1970-01-01
        相关资源
        最近更新 更多