python - Pandas 条形图 : Add marker to distinguish 0 and NaN

标签 python pandas matplotlib plot nan

我在 Python 中有以下 pandas DataFrame:

df = pd.DataFrame([10,0,np.nan,8],index=[1947,1948,1949,1950], columns=['values'])
df
      values
1947      10
1948       0
1949     NaN
1950       8

我想使用 df.plot(kind='bar') 绘制条形图。

如何添加一种标记来区分 0NaN(并将其添加到图例中)?

一般结果如下所示: Bar plot of the values from the dataframe, showing 1947 as 10, 1948 as 0, 1949 as 0 and 1950 as 8

编辑:好吧,最好是这样的: enter image description here

我尝试将“分散”选项与 firelynx 的第一个解决方案结合使用,但仍然出现一些错误...

最佳答案

可视化 nan 非常容易,如果您没有任何特定要求,这里是许多方法之一:

df['isnan'] = pd.isnull(df['values'])
df.plot(kind='bar')

enter image description here

另一种方式:

df['values'] = df['values'].fillna(-1)
df.plot(kind='bar')

enter image description here

与 pandas 绘图一样,一旦您完全想要一种方式,它就会复杂得多。

import matplotlib.pyplot as plt
import matplotlib.ticker as plticker

markers = df[df['isnan']]
fig, ax1 = plt.subplots()
ax1.bar(df.index, df['values'], 0.4, align='center')       
ax1.plot(markers.index, markers, 'ro')
loc = plticker.MultipleLocator(base=1.0)
ax1.xaxis.set_major_locator(loc)
ax1.xaxis.set_ticklabels(["","1947", "1948", "1949", "1950"])
plt.show()

enter image description here

关于python - Pandas 条形图 : Add marker to distinguish 0 and NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31555834/

相关文章:

python - 合并2个数据框在pandas中共享同一列

python - Python:什么是“变量”?

python - matplotlib 修改 colormap 以白色为零

python - 在 Python Selenium 的 xpath 中使用变量

Python - 在 if 语句中使用字符串作为条件

python - 使用 ItemLoader 但在 Scrapy 中添加 XPath、值等

python - 使用不同的预先计算的 bin 形状和频率渲染直方图

python - seaborn 散点图绘制的日期多于原始数据中存在的日期

python - 按列数据类型对 pd.describe 的输出进行排序

python - TypeError : Passing PeriodDtype data is invalid. 改为使用 `data.to_timestamp()`