You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现按艺术家筛选的产品销量占比交互式可视化?

解决方案

针对你的需求,推荐用交互式Web应用框架实现艺术家筛选+销量占比可视化,比单纯用Plotly更灵活可控。以下分R和Python两种常用场景给出具体实现:


R Shiny 实现(适配你的数据格式)

Shiny是R生态中做交互式可视化的标准工具,能轻松实现筛选控件+动态图表/表格的组合。

完整代码

library(shiny)
library(ggplot2)
library(dplyr)

# 加载你的数据集
df <- tibble::tribble(
  ~artist,        ~product,                          ~quantity_sold, ~freq,
  "Bad Waitress", "bad waitress x-large",              1, 11.1,
  "Bad Waitress", "cheaper reaper do",                 1, 11.1,
  "Bad Waitress", "cheaper reaper m",                  1, 11.1,
  "Bad Waitress", "cheaper reaper tank top",           1, 11.1,
  "Bad Waitress", "short sleeve black",                5, 55.6,
  "Black Pumas",  "capitol cuts",                      2, 50,
  "Black Pumas",  "poster",                            2, 50,
  "CMAT",         "cmat socks",                       51, 12.2,
  "CMAT",         "if my wife new i'd be dead poster",95, 22.8,
  "CMAT",         "imwn bolo tie",                    37, 8.87
)

# 重新计算占比(验证原freq列的准确性)
df <- df %>%
  group_by(artist) %>%
  mutate(calc_freq = round((quantity_sold / sum(quantity_sold)) * 100, 1)) %>%
  ungroup()

# Shiny应用结构
ui <- fluidPage(
  titlePanel("艺术家产品销量占比"),
  sidebarLayout(
    sidebarPanel(
      # 艺术家筛选下拉框
      selectInput("selected_artist", "选择艺术家:",
                  choices = unique(df$artist),
                  selected = unique(df$artist)[1])
    ),
    mainPanel(
      # 交互式饼图(展示占比)
      plotly::plotlyOutput("sales_pie"),
      # 详细数据表格
      tableOutput("sales_table")
    )
  )
)

server <- function(input, output) {
  # 动态过滤数据
  filtered_data <- reactive({
    df %>% filter(artist == input$selected_artist)
  })

  # 渲染交互式饼图
  output$sales_pie <- plotly::renderPlotly({
    filtered_data() %>%
      plotly::plot_ly(labels = ~product, values = ~calc_freq, type = "pie") %>%
      plotly::layout(title = paste(input$selected_artist, "产品销量占比"),
             showlegend = TRUE)
  })

  # 渲染详情表格
  output$sales_table <- renderTable({
    filtered_data() %>%
      select(product, quantity_sold, freq, calc_freq) %>%
      rename(原始占比 = freq, 计算占比 = calc_freq)
  })
}

# 启动应用
shinyApp(ui = ui, server = server)

Python Dash 实现

如果你习惯用Python,Dash是对应的交互式框架,搭配Plotly实现可视化:

完整代码

import pandas as pd
import dash
from dash import dcc, html, Input, Output, dash_table
import plotly.express as px

# 加载你的数据集
df = pd.DataFrame({
    'artist': ['Bad Waitress', 'Bad Waitress', 'Bad Waitress', 'Bad Waitress', 'Bad Waitress',
               'Black Pumas', 'Black Pumas', 'CMAT', 'CMAT', 'CMAT'],
    'product': ['bad waitress x-large', 'cheaper reaper do', 'cheaper reaper m',
                'cheaper reaper tank top', 'short sleeve black', 'capitol cuts',
                'poster', 'cmat socks', "if my wife new i'd be dead poster", 'imwn bolo tie'],
    'quantity_sold': [1,1,1,1,5,2,2,51,95,37],
    'freq': [11.1,11.1,11.1,11.1,55.6,50,50,12.2,22.8,8.87]
})

# 重新计算占比
df['calc_freq'] = df.groupby('artist')['quantity_sold'].transform(lambda x: round((x/x.sum())*100, 1))

# Dash应用结构
app = dash.Dash(__name__)

app.layout = html.Div([
    html.H1("艺术家产品销量占比"),
    # 艺术家筛选下拉框
    dcc.Dropdown(
        id='selected_artist',
        options=[{'label': i, 'value': i} for i in df['artist'].unique()],
        value=df['artist'].unique()[0]
    ),
    # 交互式饼图
    dcc.Graph(id='sales_pie'),
    # 详细数据表格
    dash_table.DataTable(
        id='sales_table',
        columns=[
            {'name': '产品', 'id': 'product'},
            {'name': '销量', 'id': 'quantity_sold'},
            {'name': '原始占比', 'id': 'freq'},
            {'name': '计算占比', 'id': 'calc_freq'}
        ],
        style_table={'overflowX': 'auto'}
    )
])

# 回调函数:根据选择更新图表和表格
@app.callback(
    [Output('sales_pie', 'figure'),
     Output('sales_table', 'data')],
    Input('selected_artist', 'value')
)
def update_output(selected_artist):
    filtered_df = df[df['artist'] == selected_artist]
    # 生成饼图
    fig = px.pie(filtered_df, values='calc_freq', names='product',
                 title=f"{selected_artist} 产品销量占比")
    # 生成表格数据
    table_data = filtered_df.to_dict('records')
    return fig, table_data

if __name__ == '__main__':
    app.run_server(debug=True)

方案优势

  1. 用饼图替代分组柱状图,更直观展示占比关系
  2. 内置筛选下拉框,一键切换艺术家,避免多艺术家数据拥挤
  3. 同时展示可视化图表和详细数据表格,满足不同查看需求

内容的提问来源于stack exchange,提问作者Flea

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 11:40:32