如何在Python中为绘制图形的x轴标签添加信息?

问题描述 投票:0回答:2
import pandas as pd
import matplotlib.pyplot as plt

my_funds = [10, 20, 50, 70, 90, 110]
my_friends = ['Angela', 'Gabi', 'Joanna', 'Marina', 'Xenia', 'Zulu']
my_actions = ['sleep', 'work', 'play','party', 'enjoy', 'live']
df = pd.DataFrame({'Friends': my_friends, 'Funds':my_funds, 'Actions': my_actions})

产生:

enter image description here

然后,我将其绘制如下:

df.plot (kind='bar', x = "Friends" , y = 'Funds', color='red', figsize=(5,5))

得到以下内容:

enter image description here

目标是什么?

同一张图表,而不是将“ Angela-sleep”写在x轴上,而不是“ Angela”。 “睡眠”来自“操作”列。

进一步[Gabi - work, Joanna - play, Marina - party, Xenia - enjoy, Zulu - live]

python dataframe graph charts axis-labels
2个回答
2
投票

解决方案可能是在DataFrame中创建一个新列:

df["Friend-Action"] = [f"{friend} -> {action}" for friend, action in zip(df["Friends"], df["Actions"])]

然后,绘制此列:

df.plot (kind='bar', x = "Friend-Action" , y = 'Funds', color='red', figsize=(5,5))

enter image description here


2
投票

出于这个问题,使用所需的值创建一个额外的列,然后将其传递到df.plot()会比较容易:

df['Friends_actions'] = df['Friends'] + " " + df['Actions']
df.plot(kind='bar', x = "Friends_actions" , y = 'Funds', color='red', figsize=(5,5))

输出:enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.