gpt4 book ai didi

python - 如何将这个多线图更改为条形图?

转载 作者:太空宇宙 更新时间:2023-11-03 20:37:19 25 4
gpt4 key购买 nike

我编写了一个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 文件:

源、目标、位、能量、PktCount、时间
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

最佳答案

您可以在两个列表中显式收集 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

关于python - 如何将这个多线图更改为条形图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57088256/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com