简体   繁体   English

使用pandas / matplotlib使用for循环创建条形图

[英]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循环绘制每个区域,但它显示oly图形

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. 您可以使用matplotlib创建单独的轴,然后在不同的轴上绘制每个直方图。 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. tight_layout()将确保所有标签,标题等在图中很好地适合。
  • By specifying the axes you have much more control over them. 通过指定轴,您可以更好地控制它们。

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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