如何将多线图更改为条形图?

时间:2019-07-18 06:26:12

标签: python matplotlib

我已经编写了python代码来生成多个折线图。我想将其更改为条形图,这样对于每个点(时间,pktCount),我都会获得一个条形图,以描述该时间的值。

代码

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv('C:\\Users\\Hp\\Documents\\XYZ.csv')
fig, ax = plt.subplots()
for i, group in df.groupby('Source'):
    group.plot(x='Time', y='PktCount', ax=ax,label=group["Source"].iloc[0])
ax.set_title("PktCount Sent by nodes")
ax.set_ylabel("PktCount")
ax.set_xlabel("Time (milliSeconds)")
#optionally only set ticks at years present in the years column
plt.legend(title="Source Nodes", loc=0, fontsize='medium', fancybox=True)
plt.show()

这是我的csv文件:

Source,Destination,Bits,Energy,PktCount,Time 1,3,320,9.999983999999154773195,1,0 3,1,96,9.999979199797145566758,1,1082 3,4,320,9.999963199267886912408,2,1773 4,3,96,9.999974399702292006927,1,2842 1,3,320,9.999947199998309546390,2,7832 3,1,96,9.999937599065032479166,3,8965 3,4,320,9.999921598535773824816,4,10421 4,3,96,9.999948799404584013854,2,11822 2,3,384,9.999907199998736846248,1,13796 3,2,96,9.999892798283143074166,5,14990 1,3,320,9.999886399997464319585,3,18137 3,4,384,9.999873597648032688946,6,18488 3,4,384,9.999854397012922303726,7,25385 4,3,96,9.999919999106876020781,3,26453 1,3,320,9.999831999996619092780,4,27220 3,1,96,9.999828796810067870484,8,28366 2,3,384,9.999823999997473692496,2,31677 3,2,96,9.999804796557437119834,9,32873 1,3,320,9.999787199995773865975,5,34239 3,1,96,9.999783996354582686592,10,35370 1,3,320,9.999766399994928639170,6,41536 3,1,96,9.999763196151728253350,11,42667 1,3,320,9.999745599994083412365,7,49060 3,1,96,9.999742395948873820108,12,50192 2,3,384,9.999742399996210538744,3,50720 3,2,96,9.999718395696243069458,13,51925

1 个答案:

答案 0 :(得分:0)

您可以在两个列表中显式收集x和y轴的值,然后分别绘制它们:-

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv('C:\\Users\\Hp\\Documents\\XYZ.csv')
fig, ax = plt.subplots()

x1, y1 = [], []
for i, group in df.groupby('Source'):
    #collecting all values in these lists
    x1.append(group['Time'].values.tolist()) 
    y1.append(group['PktCount'].values.tolist())

ax.set_title("PktCount Sent by nodes")
ax.set_ylabel("PktCount")
ax.set_xlabel("Time (milliSeconds)")

color_l = ['r', 'y', 'g', 'b']
i = 0
for a, b in zip(x1, y1):
    ax.bar(a, b, width = 400, color = color_l[i])
    i += 1

plt.legend(('1', '2', '3', '4'))
plt.show()

Output