Python

User Segmentation - retail data - 2 Visualization 시각화

남생이a 2024. 3. 23. 15:15

데이터 시각화

# Set seaborn style for better aesthetics
sns.set(style="whitegrid")

# Plotting an interactive bar chart with Plotly
country_sales = df.groupby('Country')['Quantity'].sum().reset_index().sort_values(by='Quantity', ascending=False)
fig = px.bar(country_sales, x='Country', y='Quantity', color='Country',
             title='Total Sales by Country',
             labels={'Quantity': 'Total Quantity Sold', 'Country': 'Country'})
fig.update_traces(marker=dict(line=dict(width=1, color='DarkSlateGrey')), opacity=0.8)
fig.update_layout(xaxis=dict(title='Country'),
                  yaxis=dict(title='Total Quantity Sold'))
fig.show()

 

seaborn 패키지의 스타일은 whtiegrid로 설정

df를 country별로 그룹화 -> 제품 수량을 합산 -> 제품 수량에 따라 내림차순으로 정렬

막대차트 생성

 

 

일별 판매 트렌드

# Plotting an interactive line chart with Plotly
daily_sales = df.groupby(pd.to_datetime(df['InvoiceDate']).dt.date)['Quantity'].sum().reset_index()
fig = go.Figure()
fig.add_trace(go.Scatter(x=daily_sales['InvoiceDate'], y=daily_sales['Quantity'],
                         mode='lines', name='Daily Sales', line=dict(color='royalblue')))
fig.update_layout(title='Daily Sales Trend',
                  xaxis=dict(title='Date'),
                  yaxis=dict(title='Total Quantity Sold'),
                  hovermode='x unified')
fig.show()

 

Plotly 활용 선그래프 생성Dai

invoicedate 컬럼을 datetime타입으로 변환하고, 날짜별로 그룹화하여 판매된 제품 수량을 합산.

날짜에 따라 정렬된 데이터 프레임으로 반환

 

국가별 상위 10개 제품의 판매량을 막대차트로 시각화

# Plotting a stacked bar chart with Plotly
top_products = df.groupby('Description')['Quantity'].sum().nlargest(10).reset_index()
top_products_country = df[df['Description'].isin(top_products['Description'])].groupby(['Description', 'Country'])['Quantity'].sum().reset_index()
fig = px.bar(top_products_country, x='Description', y='Quantity', color='Country',
             title='Top 10 Products Sales by Country',
             labels={'Quantity': 'Total Quantity Sold', 'Description': 'Product'})
fig.update_layout(barmode='stack')
fig.show()

 

 

 

 

판매량 상위 15개 제품을 수량에 따라 트리맵으로 시각화

# Plotting a treemap with Plotly
top_categories = df.groupby('Description')['Quantity'].sum().nlargest(15).reset_index()
fig = px.treemap(top_categories, path=['Description'], values='Quantity', title='Top 15 Products by Quantity')
fig.show()

 

 

 

 

제품별 발생 빈도 상위 30 제품 가로막대그래프

# Calculate the occurrence of each unique description and sort them
description_counts = df['Description'].value_counts()

# Get the top 30 descriptions
top_30_descriptions = description_counts[:30]

# Plotting
plt.figure(figsize=(18,10))
plt.barh(top_30_descriptions.index[::-1], top_30_descriptions.values[::-1], color='#ff6200')

# Adding labels and title
plt.xlabel('Number of Occurrences')
plt.ylabel('Description')
plt.title('Top 30 Most Frequent Descriptions')

# Show the plot
plt.show()

 

 

wordcloud = WordCloud(width=1500, height=400, background_color='white').generate(' '.join(df['Description'].astype(str)))
plt.figure(figsize=(18, 6))
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.title('Word Cloud of Product Descriptions')
plt.show()

 

 

 

제품별 워드 클라우드 생성 후 시각화

wordcloud = WordCloud(width=1500, height=400, background_color='white').generate(' '.join(df['Description'].astype(str)))
plt.figure(figsize=(18, 6))
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.title('Word Cloud of Product Descriptions')
plt.show()