0

here is the data and code that I'm using to plot the bar chart as shown in the output plot. The issue is with y-ticks, I need to have y-ticks aligned in a vertical manner such that they cover/coincides with all four bars. If we use rot = 'some int value' the ticks rotate, but they do not exactly align vertically covering four bars.

Polymer Depth Residual time
HPAM7030 50 1159
HPAM7030 100 1638
HPAM7030 200 2170
HPAM7030 500 2718
APAM7525 50 2040
APAM7525 100 3101
APAM7525 200 4176
APAM7525 500 5270
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.style.use(['science', 'notebook', 'grid'])
df.pivot(index = 'Polymer', columns = 'Depth', values = 'Residual time').plot(kind='barh')
plt.title('Residual time of different polymers (2 year simulation)')
plt.ylabel("Type of Polymer")
plt.xlabel("Residual time (Days)")
plt.show()

output plot

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Omi
  • 69
  • 8
  • 1
    I don't know how you rotate the labels but [here](https://stackoverflow.com/questions/10998621/rotate-axis-text-in-python-matplotlib) are various versions listed for x-labels. Those for y-labels are equivalent. You can add the keyword [`va="center"` (options: 'center' | 'top' | 'bottom' | 'baseline')](https://matplotlib.org/stable/tutorials/text/text_props.html) – Mr. T Feb 01 '22 at 11:40
  • the link is useful....if we include plt.yticks(rotation=90, va='center') it works...thanks :) – Omi Feb 01 '22 at 11:48

1 Answers1

1

I find it easier to use the Axes object returned by the pandas plotting method and set the y tick label alignment to 'center':

ax = df.pivot(index = 'Polymer', columns = 'Depth', values = 'Residual time').plot(kind='barh', rot=90)
ax.set_title('Residual time of different polymers (2 year simulation)')
ax.set(ylabel="Type of Polymer",xlabel="Residual time (Days)")
ax.set_yticklabels(ax.get_yticklabels(), va="center")

enter image description here

Stef
  • 28,728
  • 2
  • 24
  • 52
  • For both types of polymer on the y-axis, I need to have the bars aligned in increasing orders i.e 50, 100, 200 and 500 from the top of the y-axis...just to reverse the order in which they are plotted now...is it possible? – Omi Feb 03 '22 at 09:31
  • 1
    yes, just sort the columns before plotting: `df.pivot(index = 'Polymer', columns = 'Depth', values = 'Residual time').sort_values(by='Depth', axis=1, ascending=False).plot(kind='barh', rot=90)` – Stef Feb 03 '22 at 10:06
  • it works....but the legend of depth also changes and gives value in descending order starting from 500 on top and going down...is it possible to keep the legend as it is now (in the ascending manner like in the figure above)? – Omi Feb 03 '22 at 12:36
  • 1
    in this case it's easier to plot as usual and then invert the y axis: `ax = df.pivot(index = 'Polymer', columns = 'Depth', values = 'Residual time').plot(kind='barh', rot=90)` followed by `ax.invert_yaxis()`. – Stef Feb 03 '22 at 13:47