【问题标题】:ConversionError: Failed to convert value(s) to axis unitsConversionError:无法将值转换为轴单位
【发布时间】:2020-03-07 22:29:39
【问题描述】:

我有一个包含 84 行和 3 列的数据框 dd

现在我想用它绘制一个面积图,并将其索引用作 xticks,所以我执行以下操作:

dd.plot(kind='area')
plt.show()

但我得到了这个结果:

(P.S.我没有足够的声望来发图片,所以我把这个链接放在这里。)

原来有些 xticks 是自动隐藏的:应该有 84 个 xticks,但只显示了其中的 9 个(似乎是自动隐藏的)。

我发现了一个类似的问题here,但是当我尝试链接中提到的方法时,我得到了一个CnoversionError

ConversionError: Failed to convert value(s) to axis units: Index(['!', '"', '#', '$', '%', '&', ''', '(', ')', '*', '+', ',', '-', '.',
       '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<',
       '=', '>', '?', '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
       'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
       'Y', 'Z', '[', '\', ']', '^', '_', '`', 'a', 'b', 'c', 'd', 'e', 'f',
       'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't'],
      dtype='object')

我注意到我的问题与上面的链接之间的区别在于我的 DataFrame 的索引有一个 dtype object(它们是字符串),我发现如果我将索引更改为 int 列表,则错误确实消失了。

重现错误的代码:

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

dd=pd.DataFrame(np.random.rand(84,3),index=[chr(ascii) for ascii in range(33,33+84)])

dd.plot(kind='area',xticks=dd.index)

plt.show()

感谢您提前回复!

【问题讨论】:

    标签: python pandas numpy matplotlib seaborn


    【解决方案1】:
    dd=pd.DataFrame(np.random.rand(84,3),index=[chr(ascii) for ascii in range(33,33+84)])
    dd.plot(kind='area')
    plt.xticks(range(0,len(dd.index)), dd.index)
    plt.show()
    

    【讨论】:

      【解决方案2】:

      我们需要在 xticks 函数中提供标签的索引位置,标签的顺序应该按照索引位置。 xticks 函数接受 3 个参数,

      1. ticks 应该是标签索引的位置
      2. labels 参数采用标签值列表
      3. rotation 采用标签在图中的显示方式
      x = df['state']
      y = df['sales']
      tickvalues = range(0,len(x)) // or tickvalues = df.index
      plt.figure(figsize = (20,5))
      plt.xticks(ticks = tickvalues ,labels = labellist, rotation = 'vertical')
      plt.plot(x,y)
      

      【讨论】:

        猜你喜欢
        • 2023-01-03
        • 2019-07-01
        • 2023-03-14
        • 1970-01-01
        • 2016-03-26
        • 2011-09-17
        • 1970-01-01
        • 2022-11-21
        • 2017-12-04
        相关资源
        最近更新 更多