python - Pandas Plots: Separate color for weekends, pretty printing times on x axis -
i created plot looks like
i have few issues:
- how can show weekends. ways had thought grab indices corresponding weekends , draw transparent bars between xlims. rectangle drawn same. best if done plainly in pandas.
- the date formatting not pretty
following code used generate plot
ax4=df4.plot(kind='bar',stacked=true,title='mains 1 breakdown'); ax4.set_ylabel('power (w)'); idx_weekend=df4.index[df4.index.dayofweek>=5] ax.bar(idx_weekend.to_datetime(),[1800 x in range(10)]) the ax.bar highlighting weekends, not produce visible output. (problem 1) problem 2 tried use major formatter , locators, code follows:
ax4=df4.plot(kind='bar',stacked=true,title='mains 1 breakdown'); ax4.set_ylabel('power (w)'); formatter=matplotlib.dates.dateformatter('%d-%b'); locator=matplotlib.dates.daylocator(interval=1); ax4.xaxis.set_major_formatter(formatter); ax4.xaxis.set_major_locator(locator); the output produced follows: 
it may helpful know dataframe looks like
in [122]:df4 out[122]: <class 'pandas.core.frame.dataframe'> datetimeindex: 36 entries, 2011-04-19 00:00:00 2011-05-24 00:00:00 data columns: (0 6 am) dawn 19 non-null values (12 6 pm) dusk 19 non-null values (6 12 noon) morning 19 non-null values (6pm 12 noon) night 20 non-null values dtypes: float64(4)
i tried lot , these hacks work. await more pythonic , consistent solutions. solution labeling problems:
def correct_labels(ax): labels = [item.get_text() item in ax.get_xticklabels()] days=[label.split(" ")[0] label in labels] months=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"] final_labels=[] in range(len(days)): a=days[i].split("-") final_labels.append(a[2]+"\n"+months[int(a[1])-1]) ax.set_xticklabels(final_labels) also while plotting make following change
ax=df.plot(kind='bar',rot=0) this makes labels @ 0 rotation.
for finding weekends , highlighting them, wrote following 2 functions:
def find_weekend_indices(datetime_array): indices=[] in range(len(datetime_array)): if datetime_array[i].weekday()>=5: indices.append(i) return indices def highlight_weekend(weekend_indices,ax): i=0 while i<len(weekend_indices): ax.axvspan(weekend_indices[i], weekend_indices[i]+2, facecolor='green', edgecolor='none', alpha=.2) i+=2 now, plot looks more useful , covers these use cases.
Comments
Post a Comment