简体   繁体   中英

creating barplots using for loop using pandas/matplotlib

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)

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:

在此输入图像描述

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM