簡體   English   中英

如何將此多線圖更改為條形圖?

[英]How to change this multiple line graph into a bar graph?

我寫了一個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

您可以在兩個列表中顯式收集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()

輸出量

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM