【发布时间】:2018-11-02 10:28:08
【问题描述】:
我在将 pandas 数据框的第二列绘制到 twinx y 轴上时遇到了一些问题。我认为这可能是因为第二个有问题的列包含 NaN 值。 NaN 值之所以存在,是因为每 10 年只有一次数据可用,尽管第一列每年都有可用数据。它们是使用 np.nan 生成的,为了清楚起见,我将其包含在最后。
这里的直觉是将两个系列绘制在同一个 x 轴上,以显示它们随时间的趋势。
这是我的代码和数据框:
import pandas as pd
import numpy as np
import matplotlib as plt
import matplotlib.pyplot as plt
list1 = ['1297606', '1300760', '1303980', '1268987', '1333521', '1328570',
'1328112', '1353671', '1371285', '1396658', '1429247', '1388937',
'1359145', '1330414', '1267415', '1210883', '1221585', '1186039',
'884273', '861789', '857475', '853485', '854122', '848163', '839226',
'820151', '852385', '827609', '825564', '789217', '765651']
list1a = [1980, 1981, 1982, 1983, 1984, 1985, 1986, 1987, 1988, 1989, 1990, 1991,
1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003,
2004, 2005, 2006, 2007, 2008, 2009, 2010]
list3b = [121800016.0, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan,
145279588.0, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan,
160515434.5, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan,
168140487.0]
d = {'Year': list1a,'Abortions per Year': list1,
'Affiliation with Religious Institutions': list3b}
newdf = pd.DataFrame(data=d)
newdf.set_index('Year',inplace=True)
fig, ax1 = plt.subplots(figsize=(20,5))
y2min = min(newdf['Affiliation with Religious Institutions'])
y2max = max(newdf['Affiliation with Religious Institutions'])
ax1.plot(newdf['Abortions per Year'])
#ax1.set_xticks(newdf.index)
ax1b = ax1.twinx()
ax1b.set_ylim(y2min*0.8,y2max*1.2)
ax1b.plot(newdf['Affiliation with Religious Institutions'])
plt.show()
我最终得到了一个不显示第二个图的图表。 (当我将第二个图更改为具有每年的数值时,它会绘制它)。这是第二个图(带有 NaN 值)——被忽略:
感谢任何建议。
*如何为第二列生成 np.nan 值:我循环遍历索引列,并且对于没有数据的每一年,将 np.nan 返回到列表中,然后将其设为一列。
for i in range(len(list1a)):
if list1a[i] in list3a:
var = list2[j]
list3b.append(var)
j+=1
else:
var = np.nan
list3b.append(var)
【问题讨论】:
-
@James 感谢您的编辑,我在打印时用 nan(不是 np.nan)粘贴了列表
标签: python pandas matplotlib nan