4

I have below code:

def OS_Usage_Zone_Wise(data,zone): 
   data_os = data['os'].value_counts().plot("bar",figsize=(12,4),fontsize=10)
   data_os.set_title("OS usage in "+zone+" region",color='g',fontsize=20)
   data_os.set_xlabel("OS name",color='b',fontsize=20)
   data_os.set_ylabel("use count",color='b',fontsize=20)


zone = ["east","west","south","central"] 
i = 0
data_os = [data_east,data_west,data_south,data_central] 
for data in data_os:
     OS_Usage_Zone_Wise(data,zone[i])
     print("now "+zone[i])
     i = i+1

I am trying plot for every zone using a for loop,but its displaying oly graph

for 'central' zone,I understand thats it showing the last bar and not displaying

the previous ones,is there any way to plot graph for all zones using a loop(dont

want to do generate graph by using same code again and again)

2

1 Answer 1

6

You can use matplotlib to create separate axes and then plot each histogram on a different axis. Here is some sample code:

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

# Create some dummy data
data = pd.DataFrame()
zones = ["east","west","south","central"]

data['zone']=np.hstack([[zone]*np.random.randint(10,20) for zone in zones])
data['OS Usage']=np.random.random(data.shape[0])

# Now create a figure
fig, axes = plt.subplots(1,4, figsize=(12,3))

# Now plot each zone on a particular axis
for i, zone in enumerate(zones):
    data.loc[data.zone==zone].hist(column='OS Usage',
                                   bins=np.linspace(0,1,10),
                                   ax=axes[i],
                                   sharey=True)
    axes[i].set_title('OS Usage in {0}'.format(zone))
    axes[i].set_xlabel('Value')
    axes[i].set_ylabel('Count')

fig.tight_layout()
fig.show()

Which produces the following figure:

enter image description here

Notes:

  • You can use enumerate to loop through the zones and simultaneously generate an index to specify the axis used.
  • The tight_layout() will ensure all the labels, title, etc. fit nicely in the figure.
  • By specifying the axes you have much more control over them.

Hope this helps!

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

1 Comment

Thanks Robbie,I can try this approach :)

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.