如何在Python中绘制图表的x轴标签添加信息?
How to add information to the x-axis label of the plotted graph in Python?
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})
产生:
那么,我是这样画的:
df.plot (kind='bar', x = "Friends" , y = 'Funds', color='red', figsize=(5,5))
获得以下内容:
目标是什么?
同一张图,但 x 轴上写的是 "Angela - sleep" 而不是 "Angela"。 "sleep" 来自 "Action" 列。
进一步[Gabi - work, Joanna - play, Marina - party, Xenia - enjoy, Zulu - live]
一种解决方案是在您的 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))
为了这个问题,更容易创建一个包含您想要的值的额外列,然后将其传递给 df.plot()
:
df['Friends_actions'] = df['Friends'] + " " + df['Actions']
df.plot(kind='bar', x = "Friends_actions" , y = 'Funds', color='red', figsize=(5,5))
输出:
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})
产生:
那么,我是这样画的:
df.plot (kind='bar', x = "Friends" , y = 'Funds', color='red', figsize=(5,5))
获得以下内容:
目标是什么?
同一张图,但 x 轴上写的是 "Angela - sleep" 而不是 "Angela"。 "sleep" 来自 "Action" 列。
进一步[Gabi - work, Joanna - play, Marina - party, Xenia - enjoy, Zulu - live]
一种解决方案是在您的 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))
为了这个问题,更容易创建一个包含您想要的值的额外列,然后将其传递给 df.plot()
:
df['Friends_actions'] = df['Friends'] + " " + df['Actions']
df.plot(kind='bar', x = "Friends_actions" , y = 'Funds', color='red', figsize=(5,5))
输出: