Home > Net >  Bar Plot horizontally with some setting in python
Bar Plot horizontally with some setting in python

Time:01-19

I have a dataset and I want to do the bar plot horizontally in python. Here is the code which I use:

rating = [8, 4, 5, 6,7, 8, 9, 5]
objects = ('h', 'b', 'c', 'd', 'e', 'f', 'g', 'a')
y_pos = np.arange(len(objects))


plt.barh(y_pos, rating, align='center', alpha=0.5)
plt.yticks(y_pos, objects)
#plt.xlabel('Usage')
#plt.title('Programming language usage')

plt.show()

It works, however the thing that I want, I want to change the plot like this image:

enter image description here

I want to change the topest column to red. And put the yticks to a clumn like the image. Could you please help me with that? Thank you.

CodePudding user response:

This code should provide what you want.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import gridspec

rating = [8, 4, 5, 6, 7, 8, 9, 5]
objects = ['h', 'b', 'c', 'd', 'e', 'f', 'g', 'a']
y_pos = np.arange(len(objects))

fig = plt.figure(figsize=(4, 10)) 
gs = gridspec.GridSpec(1, 2, width_ratios=[1, 5], wspace=0.0)

ax= plt.subplot(gs[0])
for i in range(len(objects)): 
    ax.text(0.5, y_pos[i], objects[i], ha='center', va='center')
ax.set_xlim(0, 1)
ax.set_ylim(-0.5, len(objects)-0.5)
ax.axes.get_xaxis().set_visible(False)
ax.axes.get_yaxis().set_visible(False)

ax= plt.subplot(gs[1])
ax.barh(y_pos, rating, align='center', alpha=0.5, color=['b',]*7 ['r'])
ax.set_ylim(-0.5, len(objects)-0.5)
ax.axes.get_yaxis().set_visible(False)

plt.show()

enter image description here

  • Related