【问题标题】:Plot axvline using a dataframe column error: ValueError: The truth value of a DataFrame is ambiguous.使用数据框列错误绘制 axvline:ValueError:DataFrame 的真值不明确。
【发布时间】:2021-06-27 06:45:22
【问题描述】:

我正在尝试根据数据框的一列在散点图中添加一条水平线 - 我收到以下错误:ValueError: DataFrame 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。


x_line = datLong.groupby('ctr1').agg({'maxx': ['mean']})

for country in datLong.ctr1.unique():
    temp_df = plt.figure(country)
    temp_df = datLong[datLong.ctr1 == country]
    ax1 = temp_df.plot(kind='scatter', x='x', y='Price', color='#d95f0e', label = 'xx', linewidth =3, alpha = 0.7, figsize=(7,4))    
   
    plt.title(country)
    plt.axvline(x=x_line) ### this is the line that is causing this error
 
    plt.show()
print (ax1)

问题似乎与数据框有关。但我能弄清楚它是什么?谁能帮帮我

【问题讨论】:

  • plt.axvline 要求您传递一个数字,但 x_line 是一个数据框。
  • 谢谢,@Swier,我试图转换为 .numeric 但它不起作用(错误:在“float”和“function”实例之间不支持 >')。在这种情况下,我需要有几个值(每个值对应一个国家),想法是为每个国家地块添加线。

标签: python pandas matplotlib axvline


【解决方案1】:

x_line 包含所有国家/地区的值。使用x_line.loc[country],您将获得该国家/地区的价值。因为它返回一个数组(只有一个元素),而axvline 只接受单个值,所以您可以选择它的第一个元素 (x_line.loc[country][0])。

请注意,plt.figure 创建了一个图形,而没有 ax= 参数的 pandas plot 也会创建一个新图形。所以,要么你应该忽略plt.figure(),要么显式创建一个ax 来使用。

from matplotlib import pyplot as plt
import numpy as np
import pandas as pd

datLong = pd.DataFrame({'ctr1': np.repeat(['country 1', 'country 2'], 20),
                        'x': np.tile(np.arange(20), 2),
                        'maxx': np.random.randn(40) + 10,
                        'Price': np.random.randn(40) * 10 + 200})

x_line = datLong.groupby('ctr1').agg({'maxx': ['mean']})

for country in datLong.ctr1.unique():
    temp_df = datLong[datLong.ctr1 == country]
    ax1 = temp_df.plot(kind='scatter', x='x', y='Price', color='#d95f0e', label='xx', linewidth=3, alpha=0.7,
                       figsize=(7, 4))
    ax1.figure.canvas.set_window_title(country)
    ax1.set_title(country)
    ax1.axvline(x=x_line.loc[country][0])
    plt.show()

由于groupby 已经为每个国家/地区创建了数据框,您可以使用groupby 重写代码(不需要x_line):

for country, country_df in datLong.groupby('ctr1'):
    ax1 = country_df.plot(kind='scatter', x='x', y='Price', color='#d95f0e', label='xx', linewidth=3, alpha=0.7,
                       figsize=(7, 4))
    ax1.figure.canvas.set_window_title(country)
    ax1.set_title(country)
    ax1.axvline(x=country_df['maxx'].mean())
    plt.show()

【讨论】:

  • 非常感谢代码和解释!效果很好!
猜你喜欢
  • 2019-08-29
  • 2014-10-28
  • 2022-10-05
  • 2018-01-11
  • 1970-01-01
  • 2018-08-31
  • 2021-09-01
  • 2023-03-27
  • 2017-12-28
相关资源
最近更新 更多