为列中的每个不同条目在同一图形中绘制多行

2024-05-01 21:21:31 发布

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

我的数据集如下所示:

Town    week     price    sales       
A         1       1.1      101
A         2       1.2      303
A         3       1.3      234
B         1       1.2      987
B         2       1.5      213
B         3       3.9      423
C         1       2.4      129
C         2       1.3      238
C         3       1.3      132

现在我需要做一个单一的数字与3线(每个代表一个不同的城镇),我在那里绘制每周的销售和价格。我知道如何做到这一点,当我采取平均的城镇,但我不知道如何做到每个城镇。你知道吗

data = pd.read_excel("data.xlsx")

dfEuroAvg = data[data['Product'] == "Euro"].groupby('Week').mean()

t = np.arange(1, 50, 1)

y3 = dfEuroAvg['Sales']
y4 = dfEuroAvg['Price']

fig, ax2 = plt.subplots()

color = 'tab:green'
ax2.set_xlabel('Week')
ax2.set_ylabel('Sales', color = color)    
ax2.plot(t, y3, color = color)
ax2.tick_params(axis = 'y', labelcolor = color)

ax3 = ax2.twinx()
color = 'tab:orange'
ax3.set_ylabel('Price', color=color) 
ax3.plot(t, y4, color=color)
ax3.tick_params(axis='y', labelcolor=color)

ax2.set_title("product = Euro, Sales vs. Price")

编辑:X轴是周,Y轴是价格和销售额。你知道吗


Tags: data价格tabpricecolorsalesweekset
3条回答

您必须通过过滤数据帧分别获取每个城镇的数据。你知道吗

# df = your dataframe with all the data

towns = ['A', 'B', 'C']

for town in towns:
    town_df = df[df['town'] == town]
    plt.plot(town_df['week'], town_df['price'], label=town)

plt.legend()
plt.xlabel('Week') 
plt.ylabel('Price') 
plt.title('Price Graph')
plt.show()

输出:

enter image description here

我已经为价格图做了这些,你同样可以用同样的步骤创建一个以销售为y轴的图

你可以直接用熊猫绘制数据透视图。你知道吗

ax = df.pivot("week", "Town", "price").plot()
ax2 = df.pivot("week", "Town", "sales").plot(secondary_y=True, ax=ax)

完整示例:

import io
import pandas as pd
import matplotlib.pyplot as plt

u = """Town    week     price    sales       
A         1       1.1      101
A         2       1.2      303
A         3       1.3      234
B         1       1.2      987
B         2       1.5      213
B         3       3.9      423
C         1       2.4      129
C         2       1.3      238
C         3       1.3      132"""

df = pd.read_csv(io.StringIO(u), delim_whitespace=True)

ax = df.pivot("week", "Town", "price").plot(linestyle=" ", legend=False)
ax.set_prop_cycle(None)
ax2 = df.pivot("week", "Town", "sales").plot(secondary_y=True, ax=ax, legend=False)

ax.set_ylabel('Price')
ax2.set_ylabel('Sales')
ax2.legend()

plt.show()

enter image description here

这是一种方法,使用groupby基于Town形成组,然后使用次y轴绘制pricesales

fig, ax = plt.subplots(figsize=(8, 6))

df_group = data.groupby('Town')['week','price','sales']

ylabels = ['price', 'sales']
colors =['r', 'g', 'b']

for i, key in enumerate(df_group.groups.keys()):
    df_group.get_group(key).plot('week', 'price', color=colors[i], ax=ax, label=key)
    df_group.get_group(key).plot('week', 'sales', color=colors[i], linestyle=' ', secondary_y=True, ax=ax)

handles,labels = ax.get_legend_handles_labels()
legends = ax.legend()
legends.remove()
plt.legend(handles, labels)

ax1.set_ylabel('Price')
ax2.set_ylabel('Sales')

enter image description here

相关问题 更多 >