python - pandas show multiple bar graphs on a chart -
my data looks this:
term date change1 change2 aaa 2010-03-01 23.00 24.31 bbb 2010-03-01 25.00 0.00 ccc 2012-05-01 100.00 100.00
the date column can have repeated dates. want plot each term, change1 , change2 is. thinking have term x-axis , change1 , change2 share same y axis plotted bar charts side side. know how y axis part dont know how set x axis. each term somehow show date if possible otherwise not priority.
heres have:
fig = plt.figure() ax = fig.add_subplot(111) ax2 = ax.twinx() df.change1.plot(kind = 'bar', color = 'red', ax = ax , position = 1) df.change2.plot(kind = 'bar', color = 'blue', ax = ax2, position = 2) ax.set_ylabel= ('change1') ax2.set_ylabel=('change2') plt.show()
thanks,
one way make labels along x-axis
term
s set term
index:
df = df.set_index(['term'])
for example,
import pandas pd import matplotlib.pyplot plt df = pd.dataframe({'change1': [23.0, 25.0, 100.0], 'change2': [24.309999999999999, 0.0, 100.0], 'date': ['2010-03-01', '2010-03-01', '2012-05-01'], 'term': ['aaa', 'bbb', 'ccc']}) df = df.set_index(['term']) fig = plt.figure() ax = fig.add_subplot(111) ax2 = ax.twinx() df['change1'].plot(kind='bar', color='red', ax=ax, position=0, width=0.25) df['change2'].plot(kind='bar', color='blue', ax=ax2, position=1, width=0.25) ax.set_ylabel = ('change1') ax2.set_ylabel = ('change2') plt.show()
or, instead of setting index, set xticklabels explicitly:
import pandas pd import matplotlib.pyplot plt df = pd.dataframe({'change1': [23.0, 25.0, 100.0], 'change2': [24.309999999999999, 0.0, 100.0], 'date': ['2010-03-01', '2010-03-01', '2012-05-01'], 'term': ['aaa', 'bbb', 'ccc']}) fig = plt.figure() ax = fig.add_subplot(111) ax2 = ax.twinx() df['change1'].plot(kind='bar', color='red', ax=ax, position=0, width=0.25) df['change2'].plot(kind='bar', color='blue', ax=ax2, position=1, width=0.25) ax.set_ylabel = 'change1' ax2.set_ylabel = 'change2' labels = ['{}\n{}'.format(date, term) date, term in zip(df['date'], df['term'])] ax.set_xticklabels(labels, minor=false) fig.autofmt_xdate() plt.show()
per question in comments, create new plot each date
, iterate on groups in df.groupby(['date'])
:
import pandas pd import matplotlib.pyplot plt df = pd.dataframe({'change1': [23.0, 25.0, 100.0], 'change2': [24.309999999999999, 0.0, 100.0], 'date': ['2010-03-01', '2010-03-01', '2012-05-01'], 'term': ['aaa', 'bbb', 'ccc']}) groups = df.groupby(['date']) fig, axs = plt.subplots(nrows=groups.ngroups) groupi, ax in zip(groups,axs): index, grp = groupi ax2 = ax.twinx() grp['change1'].plot(kind='bar', color='red', ax=ax, position=0, width=0.25) grp['change2'].plot(kind='bar', color='blue', ax=ax2, position=1, width=0.25) ax.set_ylabel = 'change1' ax2.set_ylabel = 'change2' ax.set_title(index) ax.set_xticklabels(grp['term'].tolist(), minor=false, rotation=0) fig.tight_layout() plt.show()
Comments
Post a Comment