data-visualization
Create clear data visualizations with Matplotlib, Plotly, and Altair: chart selection, design, interactivity, and dashboards. Use for communicating data.
Data Visualization
Clear, honest charts and dashboards in Python.
Quick Start
pip install matplotlib plotly pandasWhen to Use
- Exploring data distributions and relationships
- Reporting metrics to stakeholders
- Building interactive dashboards
- Publishing publication-quality figures
Best Practices
Chart Selection
- Use bar charts for categories, lines for trends
- Use scatter for relationships, histograms for distributions
- Avoid 3D and pie charts for precision
- Match the chart to the question
Design
- Label axes and units clearly
- Start y-axis at zero for bars
- Use a consistent color palette
- Remove chart junk and gridlines noise
Interactivity
- Use Plotly/Altair for hover and zoom
- Link views for brushing and filtering
- Keep dashboards performant
- Provide tooltips with context
Honesty
- Don't truncate axes misleadingly
- Show uncertainty when it matters
- Use log scales deliberately
- Cite data sources
Dependencies
pip install matplotlib plotly pandas
# dashboards: pip install streamlit / dashExamples
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({"region": ["A", "B", "C"], "sales": [10, 25, 15]})
df.plot.bar(x="region", y="sales")
plt.title("Sales by region")
plt.ylabel("Sales ($k)")
plt.tight_layout()
plt.savefig("sales.png", dpi=150)import plotly.express as px
fig = px.line(df, x="month", y="revenue", color="region")
fig.update_layout(title="Revenue trend", xaxis_title="Month", yaxis_title="Revenue")
fig.show()# Distribution comparison
import plotly.graph_objects as go
fig = go.Figure()
fig.add_trace(go.Histogram(x=data_a, name="Control"))
fig.add_trace(go.Histogram(x=data_b, name="Treatment", opacity=0.6))
fig.update_layout(barmode="overlay")# Interactive scatter with hover
fig = px.scatter(df, x="ad_spend", y="revenue", color="channel", hover_data=["region"])Step-by-Step
1. Clarify the question the chart must answer.
2. Choose the right chart type for the data.
3. Prepare the data (aggregate, clean).
4. Build with Matplotlib (static) or Plotly/Altair (interactive).
5. Label axes, units, and titles.
6. Apply a consistent design system.
7. Add interactivity for exploration.
8. Review for honesty and clarity.
Validation
1. Chart answers the stated question
2. Axes and units are labeled
3. No misleading truncation or scales
4. Colors are accessible and consistent
5. Interactive views load quickly
Troubleshooting
- Cluttered charts: aggregate or filter data.
- Misleading: check axis starts and scales.
- Slow dashboards: pre-aggregate and limit data.
Data Visualization (Визуализация данных)
Ясные, честные графики и дашборды на Python.
Быстрый старт
pip install matplotlib plotly pandasКогда использовать
- Исследование распределений и связей
- Отчёты метрик стейкхолдерам
- Интерактивные дашборды
- Публикационные фигуры
Лучшие практики
Выбор графика
- Бар для категорий, линии для трендов
- Scatter для связей, histograms для распределений
- Избегайте 3D и pie для точности
- График под вопрос
Дизайн
- Подписывайте оси и единицы
- Ось Y с нуля для баров
- Консистентная палитра
- Убирайте chart junk и шум сетки
Интерактивность
- Plotly/Altair для hover и zoom
- Связывайте вьюхи для brushing/фильтров
- Производительные дашборды
- Tooltips с контекстом
Честность
- Не урезайте оси вводяще
- Показывайте неопределённость
- Лог-шкалы осознанно
- Цитируйте источники данных
Зависимости
pip install matplotlib plotly pandas
# дашборды: pip install streamlit / dashПримеры
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({"region": ["A", "B", "C"], "sales": [10, 25, 15]})
df.plot.bar(x="region", y="sales")
plt.title("Sales by region")
plt.ylabel("Sales ($k)")
plt.tight_layout()
plt.savefig("sales.png", dpi=150)import plotly.express as px
fig = px.line(df, x="month", y="revenue", color="region")
fig.update_layout(title="Revenue trend", xaxis_title="Month", yaxis_title="Revenue")
fig.show()# Сравнение распределений
import plotly.graph_objects as go
fig = go.Figure()
fig.add_trace(go.Histogram(x=data_a, name="Control"))
fig.add_trace(go.Histogram(x=data_b, name="Treatment", opacity=0.6))
fig.update_layout(barmode="overlay")# Интерактивный scatter с hover
fig = px.scatter(df, x="ad_spend", y="revenue", color="channel", hover_data=["region"])Пошаговое руководство
1. Уточните вопрос, на который должен ответить график.
2. Выберите правильный тип графика.
3. Подготовьте данные (агрегация, чистка).
4. Соберите на Matplotlib (статичный) или Plotly/Altair (интерактивный).
5. Подпишите оси, единицы и заголовки.
6. Примените консистентный дизайн-систем.
7. Добавьте интерактив для исследования.
8. Проверьте честность и ясность.
Валидация
1. График отвечает на заданный вопрос
2. Оси и единицы подписаны
3. Нет вводящего урезания или шкал
4. Цвета доступны и консистентны
5. Интерактивные вьюхи грузятся быстро
Устранение неполадок
- Захламлённые графики: агрегируйте или фильтруйте данные.
- Вводящие: проверьте старт осей и шкалы.
- Медленные дашборды: пред-агрегируйте и ограничьте данные.