資料框是我正在使用的快照。我想要實作的是不同品牌月銷售額的折線圖。數字前帶有“-”的月份表示之前最多 12 個月的月份,而數字前沒有“-”的月份表示最多 12 個月之后的月份。在折線圖上,所有“-”月份(前幾個月)將在左側,之后的月份將在右側,以 0 為中心。Count_Toy_Brand_A 是 A 公司不同 Toy_Brands 的數量,而 Count_Toy_Brand_B 是 B 公司不同 TOY_Brands 的數量。總的來說,我將為 A、B、C 繪制三個不同的折線圖,其中兩條線分別標記為 A 公司和B公司。我想知道這是否可以在熊貓中完成。任何幫助,將不勝感激。
import pandas as pd
import numpy as np
df = pd.DataFrame({
'toy_brand_A':['A', 'B', 'C'],
'count_toy_brand_A':[11, 5, 16],
'month-0_sales_A':[50, 12, 6],
'month-1_sales_A':[8,7, 6],
'month-2_sales_A':[8,7, 6],
'month1_sales_A':[20, 40, 18],
'month2_sales_A':[8,7, 6],
'count_toy_brand_B':[15, 25, 4],
'month-0_sales_B':[10, 8, 61],
'month-1_sales_B':[3,5, 90],
'month-2_sales_B':[4,7, 1],
'month1_sales_B':[30, 20, 18],
'month2_sales_B':[8,7, 6],
})

uj5u.com熱心網友回復:
嘗試先重新格式化資料:
# Removes unnecessary columns and sets new indices.
cols = df.columns[~df.columns.str.contains('count')]
df = df[cols]
df.rename(columns={'toy_brand_A': 'toy_brand'}, inplace=True)
df.set_index('toy_brand', inplace=True)
df = df.T
df['company'] = 0
df.loc[df.index.str.contains('_A'), 'company'] = 'A'
df.loc[df.index.str.contains('_B'), 'company'] = 'B'
df.index = df.index.str.replace('_A', '')
df.index = df.index.str.replace('_B', '')
輸出:
toy_brand A B C company
month-0_sales 50 12 6 A
month-1_sales 8 7 6 A
month-2_sales 8 7 6 A
month1_sales 20 40 18 A
month2_sales 8 7 6 A
month-0_sales 10 8 61 B
陰謀:
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib import pyplot as plt
plt.style.use('ggplot')
plt.figure(figsize=(10, 8))
for i, brand in enumerate(['A', 'B', 'C']):
ax = plt.subplot(2, 2, i 1)
data = df[[brand, 'company']].reset_index()
s = sns.lineplot(data=data, x='index', y=brand, hue='company', ax=ax)
s.set_xticklabels(a.index, rotation=45, ha='right')
s.set_xlabel('months', fontsize=20)
s.set_ylabel(f'Sales brand {brand}', fontsize=20)
s.set_title('My Title')
plt.tight_layout()
plt.show()

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/475971.html
標籤:Python 熊猫 matplotlib 海运
上一篇:突出顯示平行坐標圖的特定資料點
下一篇:MinIO學習
