【问题标题】:Python + Matplotlib -> NoneType error with twinxPython + Matplotlib -> Twinx 的 NoneType 错误
【发布时间】:2017-01-18 21:19:32
【问题描述】:

我想我在 matplotlib 的工作流程中遗漏了一些东西......我正在尝试创建一个自定义大小的图形,添加一些东西,然后添加第二个轴:

#temp graph
import matplotlib.pyplot as plt
plt.cla()
plt.clf()
plt.close()
df = r

fig = plt.figure(figsize=(14,6))
ax = fig.add_subplot()

#r is a dataframe filled with a bunch of data

myplot = r[r.index<=100]["TOTAL DATA"].apply(lambda x:x/1000).plot(kind='bar')
ax2 = ax.twinx()
plt.show()

这给了我以下错误:

AttributeError Traceback(最近调用 最后)在() 13 14 ---> 15 ax2 = ax.twinx() 16 17 plt.show()

AttributeError: 'NoneType' 对象没有属性 'twinx'

有什么想法吗?谢谢!

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    函数fig.add_subplot() 返回nothing (None),所以你不会有新的轴。你必须使用plt.subplots()函数,它返回一个Figure对象和一个Axes对象

    import matplotlib.pyplot as plt
    import pandas as pd
    import numpy as np
    
    plt.cla()
    plt.clf()
    plt.close()
    r = pd.DataFrame(np.random.randn(6,1),columns=['TOTAL DATA'])
    
    fig, ax= plt.subplots(figsize=(14, 6))
    
    myplot = r[r.index<=100]["TOTAL DATA"].apply(lambda x:x/1000).plot(kind='bar')
    ax2 = ax.twinx()
    plt.show()
    

    【讨论】:

      【解决方案2】:

      简单的问题。 ax 变量不是范围内的轴。我的情节是。 myplot.twinx() 有效。

      【讨论】:

      • 其实ax根本不是轴。
      • 问题中的问题与轴范围无关。如果没有给出进一步的参数,DataFrame.plot() 将简单地绘制到它找到的最后一个轴或创建一个新轴。正如其他答案中详述的那样,问题在于axNone,因为没有给add_subplot() 提供任何参数。
      【解决方案3】:

      再看问题中的尝试方向,代码中唯一的问题是ax = fig.add_subplot()返回None因为它没有给出参数

      通常的方法是调用ax = fig.add_subplot(111) 或任何其他(一组)实际创建子图的参数。 See documentation.

      因此,如果给出该参数,则问题中的代码可以正常工作。

      import matplotlib.pyplot as plt
      import pandas as pd
      r = pd.DataFrame({"TOTAL DATA" : [1000,2000,3000]})
      
      fig = plt.figure(figsize=(14,6))
      ax = fig.add_subplot(111)
      
      myplot = r[r.index<=100]["TOTAL DATA"].apply(lambda x:x/1000).plot(kind='bar')
      ax2 = ax.twinx()
      plt.show()
      

      【讨论】:

        猜你喜欢
        • 2016-05-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多