effecor
effecor

Reputation: 2043

Dataframe Bar plot with Seaborn

I'm trying to create a bar plot from a DataFrame with Datetime Index. This is an example working code:

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'])

The result is: enter image description here

As you can see the white bars cannot be distinguished well with respect of the background (why?).

I tried using instead:

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

with this result: enter image description here

But in this way I lose the automatic xticks labels (and grid) 6-months spacing.

Any idea?

Upvotes: 1

Views: 1560

Answers (2)

StupidWolf
StupidWolf

Reputation: 46978

You can just change the style:

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")

enter image description here

Upvotes: 1

david
david

Reputation: 1501

You do not actually use seaborn. Replace ax.bar(df.index, df['numbers']) with

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

Upvotes: 2

Related Questions