0

I have a data frame containing several columns for which I have continuous (annual) data since 1971 up to 2012. After that I have some say "predicted" values for 2020, 2025, 2030 and 2035. The index to the data frame is in integer format (each date), and I've tried converting it to a date time format using the appropriate module, but this still doesn't correctly space out the dates on the x-axis (to show the actual time-gaps) Here's the code I've been experimenting with:

fig, ax = plt.subplots()
# Set title
ttl = "India's fuel mix (1971-2012)"

# Set color transparency (0: transparent; 1: solid)
a = 0.7


# Convert the index integer dates into actual date objects
new_fmt.index = [datetime.datetime(year=date, month=1, day=1) for date in new_fmt.index]


new_fmt.ix[:,['Coal', 'Oil', 'Gas', 'Biofuels', 'Nuclear',    'Hydro','Wind']].plot(ax=ax,kind='bar', stacked=True, title = ttl)
ax.grid(False)
xlab = 'Date (Fiscal Year)'
ylab = 'Electricity Generation (GWh)'
ax.set_title(ax.get_title(), fontsize=20, alpha=a)
ax.set_xlabel(xlab, fontsize=16, alpha=a)
ax.set_ylabel(ylab, fontsize=16, alpha=a)

# Tell matplotlib to interpret the x-axis values as dates
ax.xaxis_date()

# Make space for and rotate the x-axis tick labels
fig.autofmt_xdate()

1 Answer 1

1

I tried to figure it out:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import datetime

# create data frame with random data (3 rows, 2 columns)
df = pd.DataFrame(np.random.randn(3,2))
# time index with missing years
t = [datetime.date(year=1971, month=12, day=31), datetime.date(year=1972, month=12, day=31), datetime.date(year=1980, month=12, day=31)]
df.index = t

# time index with all the years:
tnew = pd.date_range(datetime.date(year=1971, month=1, day=1),datetime.date(year=1981, month=1, day=1),freq="A")

# reindex data frame (missing years will be filled with NaN
df2 = df.reindex(tnew)

# replace NaN with 0
df2_zeros = df2.fillna(0)

# or interpolate
df2_interp = df2.interpolate()

# and plot
df2_interp.columns = ["coal","wind"]
df2_interp.plot(kind='bar', stacked=True)
plt.show()

Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.