我正在尝试从具有Datetime索引的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))
但是以这种方式,我失去了六个月的自动xticks标签(和网格)。
有什么主意吗?
答案 0 :(得分: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")
答案 1 :(得分:0)
您实际上并没有使用seaborn
。替换ax.bar(df.index, df['numbers'])
与
sns.barplot(df.index, df['numbers'], ax=ax)