【问题标题】:Dataframe Bar plot with SeabornSeaborn 的数据框条形图
【发布时间】:2020-08-13 10:01:03
【问题描述】:

我正在尝试从具有日期时间索引的 DataFrame 创建条形图。 这是一个示例工作代码:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
sns.set()

index = pd.date_range('2012-01-01', periods=48, freq='M')
data = np.random.randint(100, size = (len(index),1))
df = pd.DataFrame(index=index, data=data, columns=['numbers'])

fig, ax = plt.subplots()
ax.bar(df.index, df['numbers'])

结果是:

如您所见,白条在背景方面无法很好地区分(为什么?)。

我尝试改用:

df['numbers'].plot(kind='bar')
import matplotlib.ticker as ticker
ticklabels = df.index.strftime('%Y-%m')
ax.xaxis.set_major_formatter(ticker.FixedFormatter(ticklabels))

结果如下:

但是通过这种方式,我失去了 6 个月间隔的自动 xticks 标签(和网格)。

有什么想法吗?

【问题讨论】:

    标签: python python-3.x pandas matplotlib seaborn


    【解决方案1】:

    你可以改变样式:

    import matplotlib.pyplot as plt
    
    index = pd.date_range('2012-01-01', periods=48, freq='M')
    data = np.random.randint(100, size = (len(index),1))
    df = pd.DataFrame(index=index, data=data, columns=['numbers'])
    
    plt.figure(figsize=(12, 5))
    plt.style.use('default')
    plt.bar(df.index,df['numbers'],color="red")
    

    【讨论】:

      【解决方案2】:

      您实际上并没有使用seaborn。替换ax.bar(df.index, df['numbers'])

      sns.barplot(df.index, df['numbers'], ax=ax)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-09-05
        • 2015-12-08
        • 1970-01-01
        • 1970-01-01
        • 2017-10-24
        • 2016-12-18
        • 2017-10-01
        相关资源
        最近更新 更多