kaggle学习数据分析-Learn How to Group Data for Categorical Analysis with Seaborn and Pandas!
Learn How to Group Data for Categorical Analysis with Seaborn and Pandas
Overview
Most business and research questions are comparisons between groups: Which day brings the biggest tips? Do smokers and non-smokers order differently? Which discovery method finds the most planets? To answer them you need to split a table into groups, summarize each group, and show the result so that the differences are easy to see. Pandas does the splitting and summarizing withgroupby,crosstab, andpivot_table, and Seaborn draws the comparison with categorical plots such ascountplot,barplot,boxplot, andheatmap. In this material you will learn how to prepare categorical columns, group and aggregate data, build contingency tables, turn numbers into categories, plot groups with Seaborn (including the cases where Seaborn groups for you), show proportions, build heatmaps from grouped data, check whether differences are more than chance, and avoid the common mistakes.
Who this is for:Python users who can load a DataFrame and draw a basic plot, and want to compare groups correctly.
原文地址:https://www.kaggle.com/discussions/questions-and-answers/756668
Prerequisites:Basic Python, Pandas fundamentals (columns, filtering), and a basic Seaborn plot.
What you will be able to do after this material:
- Set up categorical columns with a sensible order
- Group and summarize data with
groupbyand named aggregation - Build cross-tabs and pivot tables
- Create categories from numbers and combine rare categories
- Choose the right Seaborn categorical plot for a question
- Compare groups with
hue,order, and panels - Plot a summary table without aggregating twice
- Show proportions and composition
- Draw heatmaps from grouped data and test a difference
Structure:
| Module | Topic |
|---|---|
| 1 | Grouping and categorical analysis |
| 2 | Categorical columns in Pandas |
| 3 | groupby and aggregation |
| 4 | Cross-tabs and pivot tables |
| 5 | Creating and cleaning categories |
| 6 | Seaborn plots that group for you |
| 7 | Comparing groups with hue, order, and panels |
| 8 | Plotting pre-aggregated tables |
| 9 | Proportions and composition |
| 10 | Heatmaps and testing differences |
| 11 | Common problems |
| 12 | Capstone project and best practices |
The examples use datasets in the style of Seaborn's built-in tables:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_theme(style="whitegrid")
tips = sns.load_dataset("tips")
titanic = sns.load_dataset("titanic")
planets = sns.load_dataset("planets")
Module 1: Grouping and Categorical Analysis
Objectives
- Define a categorical variable
- Describe the split, apply, combine idea
- Match question types to analyses
Lesson
Acategorical variabletakes a limited set of labels, such as the day of the week, a product line, or a region. Anumeric variabletakes measured values, such as a bill or a weight. Categorical analysis compares the numeric or count behavior of the groups that a categorical variable defines.
Pandas follows a three-step pattern, calledsplit, apply, combine:
| Step | What happens | Example |
|---|---|---|
| Split | Divide the rows into groups | One group per day |
| Apply | Calculate a summary for each group | The mean of the bills |
| Combine | Collect the results in one table | A table with one row per day |
tips.groupby("day", observed=True)["total_bill"].mean()
The kinds of questions, and where to look:
| Question | Analysis | Typical plot |
|---|---|---|
| How many rows are in each group? | Counts | countplot |
| What is the average per group? | Mean or median by group | barplot,pointplot |
| How spread out is each group? | Distribution by group | boxplot,violinplot |
| How do two categories relate? | Cross-tab | Stacked bars,heatmap |
| What share does each group hold? | Proportions | 100 percent bars |
| Is the difference real? | A test | Plot plus a test |
Two habits protect the analysis: always check the group sizes (a mean of three rows is not reliable), and always show spread, not only the average.
Takeaway
Grouping splits the data, summarizes each part, and combines the results, and every comparison needs the group sizes beside the averages.
Exercise 1
List three questions about thetipsdata that compare groups, and name the analysis and plot for each.
Module 2: Categorical Columns in Pandas
Objectives
- Inspect the categories in a column
- Use the
categorytype and ordered levels - Know why order and type matter
Lesson
Start by looking at a categorical column:
print(tips["day"].value_counts())
print(tips["day"].nunique(), tips["day"].unique())
print(tips.dtypes)
| Code | What it shows |
|---|---|
value_counts() |
Rows per category |
value_counts(normalize=True) |
Share of each category |
nunique() |
Number of distinct categories |
unique() |
The categories themselves |
isna().sum() |
Missing labels |
Thecategorytypestores a column as a fixed set of levels. It saves memory, and it lets you set an order, which Seaborn uses for axes and legends:
levels = ["Thur", "Fri", "Sat", "Sun"]
tips["day"] = pd.Categorical(tips["day"], categories=levels, ordered=True)
print(tips["day"].cat.categories)
print(tips["day"].min(), tips["day"].max())
An ordered category lets you compare (Thursday is before Sunday) and sort in the natural order, not alphabetically.
Convert a text column:
titanic["class"] = titanic["class"].astype("category")
titanic["embark_town"] = titanic["embark_town"].astype("category")
Unused levelsshow up in group results as empty groups, because Pandas keeps every level. If you filter the data, remove the empty levels:
weekend = tips[tips["day"].isin(["Sat", "Sun"])].copy()
weekend["day"] = weekend["day"].cat.remove_unused_categories()
print(weekend["day"].value_counts())
Takeaway
Use thecategorytype with a deliberate order, and remove empty levels after filtering.
Exercise 2
Convertsizeinto an ordered category, then filter to parties of four or more and remove the unused levels.
Module 3: groupby and Aggregation
Objectives
- Use
groupbywith one or several functions - Name the output columns
- Add group statistics back to the rows
Lesson
Group, choose a column, and apply a function:
tips.groupby("day", observed=True)["tip"].mean()
observed=Truelimits the result to categories that actually occur. Without it, Pandas keeps empty category levels, and recent versions warn about the default.
Several functions at once:
tips.groupby("day", observed=True)["tip"].agg(["count", "mean", "median", "std"])
Named aggregationgives readable column names and lets each column have its own function:
summary = (
tips.groupby("day", observed=True)
.agg(
n=("tip", "size"),
avg_bill=("total_bill", "mean"),
median_tip=("tip", "median"),
max_party=("size", "max"),
)
.reset_index()
)
print(summary)
reset_index()turns the group labels from the index into a normal column, which is the shape Seaborn expects.
Several grouping columns:
by_two = tips.groupby(["day", "time"], observed=True)["total_bill"].agg(["count", "mean"]).reset_index()
Add group statistics to every rowwithtransform, which keeps the original shape:
tips["day_mean_bill"] = tips.groupby("day", observed=True)["total_bill"].transform("mean")
tips["share_of_day"] = tips["total_bill"] / tips.groupby("day", observed=True)["total_bill"].transform("sum")
Filter whole groups.Keep only groups with enough rows:
big_enough = tips.groupby("size", observed=True).filter(lambda g: len(g) >= 10)
Takeaway
Use named aggregation for readable summaries,reset_indexto make them plot-ready, andtransformto attach group values to rows.
Exercise 3
Build a summary bysmokerwith the count, mean tip, and the highest bill, and add each row's share of its group's total.
Module 4: Cross-Tabs and Pivot Tables
Objectives
- Count combinations of two categories
- Build pivot tables of averages
- Turn counts into percentages
Lesson
Across-tabcounts the rows for every combination of two categories:
counts = pd.crosstab(tips["day"], tips["smoker"])
print(counts)
Add totals, or turn counts into shares:
pd.crosstab(tips["day"], tips["smoker"], margins=True)
pd.crosstab(tips["day"], tips["smoker"], normalize="index") # each row sums to 1
pd.crosstab(tips["day"], tips["smoker"], normalize="columns") # each column sums to 1
pd.crosstab(tips["day"], tips["smoker"], normalize="all") # all cells sum to 1
normalize |
Answers |
|---|---|
"index" |
Within each day, what share smoke? |
"columns" |
Among smokers, what share is on each day? |
"all" |
What share of all parties is each combination? |
Pivot tablessummarize a numeric column over two categories:
table = tips.pivot_table(
index="day", columns="time", values="total_bill",
aggfunc="mean", observed=True, margins=True,
)
print(table.round(2))
Use several functions or values:
tips.pivot_table(index="day", columns="smoker", values=["tip", "total_bill"], aggfunc="mean", observed=True)
tips.pivot_table(index="day", columns="time", values="tip", aggfunc=["count", "mean"], observed=True)
Missing combinationsappear asNaNin a pivot table, and as zero in a cross-tab. ANaNmeans no rows exist, which is different from an average of zero:
print(table.isna().sum().sum())
Takeaway
Usecrosstabfor counts and shares of two categories,pivot_tablefor averages, and melt a grid back to long form for plotting.
Exercise 4
Build a cross-tab ofsexbysmokerwith percentages by row, and a pivot table of mean tips by day and time.
Module 5: Creating and Cleaning Categories
Objectives
- Turn a number into categories with bins
- Combine rare categories
- Fix messy labels
Lesson
Fixed binswithpd.cutturn a number into labeled ranges:
tips["bill_band"] = pd.cut(
tips["total_bill"],
bins=[0, 10, 20, 30, 100],
labels=["Under 10", "10 to 20", "20 to 30", "Over 30"],
)
print(tips["bill_band"].value_counts().sort_index())
Bins include the right edge by default, so a bill of exactly 20 falls in the "10 to 20" band. Useright=Falsefor the opposite.
Equal-sized groupswithpd.qcutput the same number of rows in each group:
tips["bill_quartile"] = pd.qcut(tips["total_bill"], 4, labels=["Q1", "Q2", "Q3", "Q4"])
Name the bins in a way that the reader understands, and check that no value falls outside them, because values outside the bins become missing:
print(tips["bill_band"].isna().sum())
Combine rare categories.A categorical plot with many tiny groups is unreadable. Theplanetstable has a few common methods and several that appear only a handful of times:
print(planets["method"].value_counts())
top = planets["method"].value_counts().nlargest(3).index
planets["method_group"] = planets["method"].where(planets["method"].isin(top), "Other")
print(planets["method_group"].value_counts())
Map and clean labels:
labels = pd.Series(["Male", "male ", "M", "female", "F"])
clean = labels.str.strip().str.lower().replace({"m": "male", "f": "female"})
print(clean.value_counts())
A mapping withmapturns any value not in the mapping into missing, so always check for newNaNvalues afterward:
mapping = {"Thur": "Weekday", "Fri": "Weekday", "Sat": "Weekend", "Sun": "Weekend"}
tips["day_type"] = tips["day"].astype(str).map(mapping)
print(tips["day_type"].isna().sum())
Takeaway
Create categories withcutorqcut, combine rare ones into "Other", and check for values that fell out of your rules.
Exercise 5
Create age groups fromtitanic["age"]withpd.cut, and count the passengers in each group, including those with a missing age.
Module 6: Seaborn Plots That Group for You
Objectives
- Match a categorical plot to a question
- Let Seaborn summarize the groups
- Control the summary and the error bars
Lesson
Seaborn's categorical functions take the raw table, and group and summarize inside the plot.
| Question | Function | What it draws |
|---|---|---|
| How many rows per category? | countplot |
Bars of counts |
| Typical value per category | barplot,pointplot |
A mean (or other summary) with an interval |
| Spread per category | boxplot,violinplot,boxenplot |
The distribution |
| Every observation | stripplot,swarmplot |
One point per row |
| Several of these in a grid | catplot |
Any of the above, with panels |
sns.countplot(data=tips, x="day")
sns.barplot(data=tips, x="day", y="total_bill")
sns.boxplot(data=tips, x="day", y="total_bill")
sns.violinplot(data=tips, x="day", y="total_bill", inner="quart")
sns.swarmplot(data=tips, x="day", y="total_bill", size=3)
The summary inbarplotandpointplotis a mean with a 95 percent bootstrap confidence interval by default. Change it:
sns.barplot(data=tips, x="day", y="tip", estimator="median", errorbar=("pi", 50))
sns.barplot(data=tips, x="day", y="tip", errorbar="sd")
sns.barplot(data=tips, x="day", y="tip", errorbar=None)
The confidence interval and the standard deviation answer different questions. The interval says how well the average is known, and the standard deviation says how much individual rows vary. Say which one you show.
Show the points with the summary, because a bar hides the distribution:
ax = sns.boxplot(data=tips, x="day", y="total_bill", color="0.9", showfliers=False)
sns.stripplot(data=tips, x="day", y="total_bill", size=3, color="0.3", alpha=0.6, ax=ax)
Add counts to the barsso that the reader sees the group sizes:
ax = sns.countplot(data=tips, x="day")
ax.bar_label(ax.containers[0])
Takeaway
Seaborn groups and summarizes inside the plot, so choose the function by the question and be clear about the summary and the error bar.
Exercise 6
Draw the tip by day as a bar of the median with a 50 percent percentile interval, and again as a box plot with the points on top.
Module 7: Comparing Groups with hue, order, and Panels
Objectives
- Add a second category with
hue - Control the order of the groups
- Split into panels
Lesson
A second categoryis added withhue, which splits each group into colored sub-groups:
sns.barplot(data=tips, x="day", y="tip", hue="sex")
sns.boxplot(data=tips, x="day", y="total_bill", hue="smoker")
Useful options:
Order.The default follows the data, which may not be meaningful. Set it explicitly:
sns.barplot(data=tips, x="day", y="tip", order=["Thur", "Fri", "Sat", "Sun"])
Order by the value you are showing:
order = tips.groupby("day", observed=True)["tip"].mean().sort_values(ascending=False).index
sns.barplot(data=tips, x="day", y="tip", order=order)
A sorted bar chart is easiest to read for unordered categories, and a natural order (days, months, sizes) is best when one exists.
Panelssplit the data by a category and keep the plots uncrowded:
sns.catplot(data=tips, x="day", y="tip", col="time", kind="box", height=3.5, aspect=1)
sns.catplot(data=tips, x="day", y="tip", hue="sex", col="smoker", kind="bar", height=3.5)
Keep the number of groups readable.A rule of thumb is no more than 5 colors in ahueand no more than about 12 bars along an axis. Combine small groups into "Other" (Module 5), or show the top few.
Keep the same colors for the same category in every figure by using a palette dictionary:
palette = {"Male": "tab:blue", "Female": "tab:orange"}
sns.barplot(data=tips, x="day", y="tip", hue="sex", palette=palette)
Takeaway
Usehuefor a second category, set the order deliberately, and move to panels when the plot gets crowded.
Exercise 7
Draw tips by day and sex withhue, sorted by the average tip, and then as panels by sex.
Module 8: Plotting Pre-Aggregated Tables
Objectives
- Plot a summary table you built with Pandas
- Avoid aggregating twice
- Know when to summarize first
Lesson
Often you build the summary yourself, for example to add counts or to calculate something Seaborn does not offer. Then you plot the summary:
summary = tips.groupby("day", observed=True).agg(avg_tip=("tip", "mean"), n=("tip", "size")).reset_index()
sns.barplot(data=summary, x="day", y="avg_tip", errorbar=None)
The key iserrorbar=None. Seaborn'sbarplotaggregates by default, and with one row per category there is nothing to estimate an interval from, so the error bar is meaningless. Turning it off avoids a misleading plot.
The double-aggregation trap.If the summary table has several rows per category,barplotaverages them again, and the bar is a mean of means:
by_two = tips.groupby(["day", "sex"], observed=True)["tip"].mean().reset_index()
sns.barplot(data=by_two, x="day", y="tip", errorbar=None) # averages the two sex values per day
This is not the average tip of the day, because it ignores how many rows eachsexgroup has. Pass the raw table instead, or usehueso that the groups stay separate:
sns.barplot(data=by_two, x="day", y="tip", hue="sex", errorbar=None)
A weighted averagecannot come frombarplot. Calculate it, and plot the result:
def weighted_mean(group):
return (group["tip"] * group["size"]).sum() / group["size"].sum()
weighted = tips.groupby("day", observed=True).apply(weighted_mean, include_groups=False).rename("tip_per_person_weighted").reset_index()
sns.barplot(data=weighted, x="day", y="tip_per_person_weighted", errorbar=None)
Takeaway
Plot a summary witherrorbar=None, never feedbarplota table with several rows per bar by accident, and show the group sizes.
Exercise 8
Plot the average bill by day and sex from a summary table, once incorrectly (averaging again) and once correctly withhue, and compare the bars.
Module 9: Proportions and Composition
Objectives
- Show shares instead of counts
- Draw stacked and 100 percent bars
- Compare composition across groups
Lesson
Counts compare sizes, and proportions compare composition. If groups differ in size, shares are fairer.
Counts by two categories, side by side:
sns.countplot(data=tips, x="day", hue="smoker")
Shares within each groupfrom a cross-tab:
shares = pd.crosstab(tips["day"], tips["smoker"], normalize="index")
shares.plot(kind="bar", stacked=True, figsize=(6, 4), rot=0)
A 100 percent stacked barin Seaborn usesmultiple="fill":
sns.histplot(data=tips, x="day", hue="smoker", multiple="fill", shrink=0.8)
The y-axis then shows the share of each day that is smokers and non-smokers, so every bar has the same height, and only the split inside the bar differs.
Show the proportion as a bar plot.A mean of a true or false column is a proportion:
titanic["survived_flag"] = titanic["survived"].astype(bool)
sns.barplot(data=titanic, x="class", y="survived", hue="sex", errorbar=("ci", 95))
The height of each bar is the survival rate, and the interval shows how well it is known. Small groups have wide intervals, which is a useful warning.
Order by the proportion:
rate = titanic.groupby("class", observed=True)["survived"].mean().sort_values(ascending=False)
sns.barplot(data=titanic, x="class", y="survived", order=rate.index)
Cautions:
| Caution | Reason |
|---|---|
| Show the counts too | A 100 percent bar of 4 rows looks as solid as one of 400 |
| Keep the category order consistent | Readers compare the same stack position |
| Limit the number of colors | More than 5 stacked segments are hard to compare |
| Start the axis at zero | Bars must start at zero to be honest |
Takeaway
Use shares when groups differ in size, show the counts alongside, and keep stacks to a few segments.
Exercise 9
Draw the share of survivors by class and sex, ordered by survival rate, with the interval shown.
Module 10: Heatmaps and Testing Differences
Objectives
- Show a grouped table as a heatmap
- Annotate and scale the colors
- Test whether a difference is likely to be chance
Lesson
When two categories define a grid, aheatmapshows the pattern at a glance. Build the grid withpivot_tableorcrosstab, and pass it tosns.heatmap:
grid = tips.pivot_table(index="day", columns="time", values="total_bill", aggfunc="mean", observed=True)
sns.heatmap(grid, annot=True, fmt=".1f", cmap="mako", cbar_kws={"label": "Mean bill ($)"})
For shares:
shares = pd.crosstab(tips["day"], tips["smoker"], normalize="index")
sns.heatmap(shares, annot=True, fmt=".0%", cmap="rocket_r", vmin=0, vmax=1)
Show the group sizenext to the average by drawing two heatmaps:
counts = pd.crosstab(tips["day"], tips["time"])
fig, axes = plt.subplots(1, 2, figsize=(9, 3.5))
sns.heatmap(grid, annot=True, fmt=".1f", cmap="mako", ax=axes[0])
sns.heatmap(counts, annot=True, fmt="d", cmap="Greys", cbar=False, ax=axes[1])
axes[0].set_title("Mean bill")
axes[1].set_title("Number of parties")
Cells with very few rows should not be trusted, however vivid the color.
Test whether two categories are relatedwith a chi-square test of independence. It compares the observed counts with the counts expected if the categories were unrelated:
from scipy.stats import chi2_contingency
table = pd.crosstab(tips["day"], tips["smoker"])
chi2, p_value, dof, expected = chi2_contingency(table)
print(round(chi2, 2), round(p_value, 4), dof)
print(expected.min().round(1))
| Result | Reading |
|---|---|
| A small p-value (for example below 0.05) | The data are unlikely if the categories were unrelated |
| A large p-value | The data are consistent with no relationship |
| Smallest expected count below 5 | The test is unreliable, combine categories or use another test |
Takeaway
Use heatmaps to show grids of averages or shares with counts beside them, and use a test only to complement the plot.
Exercise 10
Build a heatmap of mean tip by day and size, show the counts beside it, and run a chi-square test ondayandtime.
Module 11: Common Problems
Objectives
- Diagnose frequent issues
- Apply short fixes
Lesson
| Problem | Cause | Fix |
|---|---|---|
| Groups appear with zero rows | Unused category levels | observed=True, orremove_unused_categories() |
| Groups missing from a result | Missing labels are dropped | fillna("Unknown"), ordropna=Falseingroupby |
| Categories in alphabetical order | Text type | OrderedCategorical, ororder= |
| Group labels are in the index | Result ofgroupby |
reset_index() |
| An error bar on a summary bar | barplothas nothing to estimate |
errorbar=None |
| A mean of means | Summary table has several rows per bar | Plot the raw table, or usehue |
| Bars look equal but groups differ in size | Averages hide the counts | Shownin the labels |
| Too many tiny groups | Rare categories | Combine into "Other" |
| Heatmap cells look reliable but are not | Few rows behind the cell | Show the count beside it |
FutureWarningaboutobserved |
Default is changing in Pandas | Setobserved=Trueexplicitly |
A quick check before plotting any grouped comparison:
def group_check(df, group, value):
result = df.groupby(group, observed=True)[value].agg(["count", "mean", "std"]).round(2)
result["share"] = (result["count"] / result["count"].sum()).round(3)
return result
print(group_check(tips, "day", "tip"))
Takeaway
Most grouping problems come from empty or missing categories, aggregating twice, and ignoring group sizes.
Exercise 11
Find and fix three problems in a grouped plot with alphabetical days, an error bar on a summary, and one tiny group.
Module 12: Capstone Project and Best Practices
Capstone project
Using a dataset with at least two categorical columns and one numeric column:
- Inspect the categorical columns, and set a deliberate order for each.
- Build a summary with
groupbyand named aggregation, including the group sizes. - Create a binned category from a numeric column with
cutorqcut. - Combine rare categories into "Other" with a stated cutoff.
- Build a cross-tab with shares and a pivot table of averages.
- Draw
countplot,barplot, andboxplotcomparisons, with the points shown. - Add a second category with
hue, then split by panels. - Plot a pre-aggregated summary correctly, with
errorbar=None. - Show composition with a 100 percent bar and a heatmap with the counts beside it.
- Test one difference, and write a short caption stating the groups, the summary, the interval, and the test.
Best Practices Summary
- Inspect categorical columns first, and set an order that carries meaning.
- Use
observed=Trueand remove unused levels, so empty groups do not appear. - Use named aggregation, and
reset_index()before plotting. - Always show the group sizes next to the averages.
- Combine rare categories into "Other", and state the cutoff.
- Choose the plot by the question: counts, typical value, spread, or composition.
- Show the distribution, not only the mean, and say whether the interval is a confidence interval or a spread.
- Plot a summary table with
errorbar=None, and avoid feeding it several rows per bar. - Use shares when groups differ in size, and show the counts too.
- Keep the number of colors and bars readable, and keep colors consistent across figures.
- Use heatmaps for grids, with the counts and a fixed color range.
- Use a test to complement the plot, never to replace it.
Quick Reference
| Task | Code |
|---|---|
| Counts per category | df["c"].value_counts() |
| Ordered category | pd.Categorical(col, categories=levels, ordered=True) |
| Group and summarize | df.groupby("c", observed=True)["v"].mean() |
| Named aggregation | .agg(n=("v", "size"), avg=("v", "mean")) |
| Make a plot-ready table | .reset_index() |
| Add group value to rows | .transform("mean") |
| Cross-tab | pd.crosstab(df["a"], df["b"], normalize="index") |
| Pivot table | df.pivot_table(index="a", columns="b", values="v", aggfunc="mean", observed=True) |
| Fixed bins | pd.cut(col, bins=[...], labels=[...]) |
| Equal-sized groups | pd.qcut(col, 4, labels=[...]) |
| Combine rare | col.where(col.isin(top), "Other") |
| Counts plot | sns.countplot(data=df, x="c") |
| Mean with interval | sns.barplot(data=df, x="c", y="v") |
| Median | estimator="median" |
| Distribution | sns.boxplot(...),sns.violinplot(...) |
| Second category | hue="c2" |
| Panels | sns.catplot(..., kind="box", col="c2") |
| 100 percent bars | sns.histplot(..., multiple="fill") |
| Heatmap | sns.heatmap(grid, annot=True, fmt=".1f") |
| Chi-square test | chi2_contingency(pd.crosstab(a, b)) |
Summary
Grouping data turns a table into comparisons. Prepare the categorical columns with a deliberate order, then usegroupbywith named aggregation to summarize each group,crosstabandpivot_tablefor two categories, andcut,qcut, and an "Other" bucket to create readable groups. Seaborn's categorical plots can group and summarize for you, so choose the function by the question (counts, typical value, spread, or composition), add a second category withhueor panels, set the order on purpose, and be clear about whether the error bar shows uncertainty or spread. When you plot a summary you built yourself, turn off the error bar and avoid averaging twice. Shares, 100 percent bars, and heatmaps show composition, always with the group sizes beside them, and a test can complement the picture. A strong categorical analysis states the groups, the summary, the interval, and the sample sizes.
This lesson is part of thePandas CourseandSeaborn Courseoffered byWisen IT Solutions, Chennai, India.
学习资料见知识星球。
以上就是今天要分享的技巧,你学会了吗?若有什么问题,欢迎在下方留言。
快来试试吧,小琥 my21ke007。获取 1000个免费 Excel模板福利!
更多技巧, www.excelbook.cn
欢迎 加入 零售创新 知识星球,知识星球主要以数据分析、报告分享、数据工具讨论为主;
1、价值上万元的专业的PPT报告模板。
2、专业案例分析和解读笔记。
3、实用的Excel、Word、PPT技巧。
4、VIP讨论群,共享资源。
5、优惠的会员商品。
6、一次付费只需129元,即可下载本站文章涉及的文件和软件。

