如何在matplotlib中绘制数值

2024-04-24 11:04:10 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有这样的数据库:

     Time Type  Profit
2      82  s/l   -51.3
5       9  t/p  164.32
8      38  s/l  -53.19
11     82  s/l   -54.4
14    107  s/l  -54.53
..    ...  ...     ...
730   111  s/l  -70.72

731   111  s/l  -70.72
732   111  s/l  -70.72
733   113  s/l  -65.13
734   113  s/l  -65.13

[239 rows x 3 columns]

我想画一张图表,显示X为时间(已经是周时),Y为利润(可以是正的也可以是负的)。对于Y,我希望每小时(X)有2个酒吧,以显示利润。在这种情况下,负利润也将是正的,但在另一个酒吧

例如,我们有-65和70。它们在图表上显示为65和70,但损失将有不同的条形图颜色

这是我目前的代码:

#reading the csv file
data = pd.read_csv(filename)
df = pd.DataFrame(data, columns = ['Time','Type','Profit']).astype(str)

#turns time column into hours of week
df['Time'] = df['Time'].apply(lambda x: findHourOfWeek(x))

#Takes in winning trades (t/p) and losing trades(s/l)
df = df[(df['Type'] == 't/p') | (df['Type'] == 's/l')]



#Plots the chart
ax = df.plot(title='Profits and Losses (Hour Of Week)',kind='bar')
#ax.legend(['Losses', 'Winners'])
plt.xlabel('Hour of Week')
plt.ylabel('Amount Of Profit/Loss')
plt.show()

Tags: columnsofcsvthedfdatatimetype
1条回答
网友
1楼 · 发布于 2024-04-24 11:04:10

您可以按分组、取消堆叠和打印:

(df.groupby(['Time','Type']).Profit.sum().abs()
   .unstack('Type')
   .plot.bar()
)

对于上面的示例数据,输出为:

enter image description here

相关问题 更多 >