Sakura Chart

A free web tool that automatically creates statistical charts from pasted CSV data

Matplotlib Basics: Creating Charts with Python

Matplotlib is one of the most widely used Python libraries for data visualization. It can create line charts, bar charts, scatter plots, histograms, box plots, and many other figures directly from code.

This guide takes you from installation to your first chart, then covers styling, saving images, common problems, and the practical differences between Matplotlib, Excel, and the no-code Sakura Chart tool.

Contents

  1. What Matplotlib is
  2. Installation
  3. Your first line chart
  4. Figure and Axes
  5. Common chart types
  6. CSV and Excel data
  7. Styling a chart
  8. Saving an image
  9. Font problems
  10. Common problems
  11. Choosing the right tool

1. What Is Matplotlib?

Matplotlib is a Python visualization library commonly used with NumPy and pandas. It is useful for data analysis, research, production monitoring, and automated report generation.

  • Repeat the same chart design with new datasets
  • Control colors, lines, axes, legends, annotations, and layouts
  • Export figures as PNG, SVG, PDF, and other formats
  • Arrange several charts in a single Figure

Its main tradeoff is that you generally create and edit charts through Python code rather than direct on-screen controls.

2. Install Matplotlib

With Python installed, run the following command in a terminal or command prompt:

Terminal / Command Prompt
python -m pip install matplotlib

In an Anaconda environment, you can use:

Anaconda
conda install matplotlib

Then import pyplot with its conventional alias:

Python
import matplotlib.pyplot as plt

3. Create Your First Line Chart

A minimal line chart
import matplotlib.pyplot as plt

month = [1, 2, 3, 4, 5]
sales = [120, 150, 135, 180, 210]

fig, ax = plt.subplots()
ax.plot(month, sales, marker="o")
ax.set_xlabel("Month")
ax.set_ylabel("Sales")
ax.set_title("Monthly Sales")

plt.show()

ax.plot() draws the line, the setter methods add labels and a title, and plt.show() displays the completed figure.

4. Understand Figure and Axes

ObjectRoleThink of it as
FigureThe container for the complete imageThe whole canvas
AxesThe region where data is plottedOne chart with coordinate axes
Create one Figure and one Axes
fig, ax = plt.subplots(figsize=(7, 4))

For several charts, specify rows and columns, such as plt.subplots(2, 2). The explicit fig and ax style is especially helpful for reusable code and multi-chart layouts.

5. Common Chart Types and Methods

PurposeChartMain method
Change over timeLine chartax.plot(x, y)
Compare categoriesBar chartax.bar(x, height)
Relationship between variablesScatter plotax.scatter(x, y)
Distribution of valuesHistogramax.hist(data)
Median, spread, and outliersBox plotax.boxplot(data)
Share of a wholePie chartax.pie(values)
Arrange four charts in one Figure
import matplotlib.pyplot as plt
import numpy as np

x = np.arange(1, 6)
y = np.array([12, 19, 15, 24, 28])
group_a = np.array([11, 13, 12, 16, 15, 18])
group_b = np.array([8, 10, 9, 11, 12, 13])

fig, axes = plt.subplots(2, 2, figsize=(10, 6), layout="constrained")

axes[0, 0].plot(x, y, marker="o", color="#be3455")
axes[0, 0].set_title("Line")

axes[0, 1].bar(x, y, color="#e78aa0")
axes[0, 1].set_title("Bar")

axes[1, 0].scatter(x, y, color="#2563eb", s=55)
axes[1, 0].set_title("Scatter")

axes[1, 1].boxplot(
    [group_a, group_b],
    tick_labels=["A", "B"],
    patch_artist=True,
    boxprops={"facecolor": "#f8d7df", "edgecolor": "#9f1239"},
    medianprops={"color": "#9f1239", "linewidth": 2}
)
axes[1, 1].set_title("Box plot")

for ax in axes.flat:
    ax.grid(axis="y", linestyle="--", alpha=0.25)
    ax.spines[["top", "right"]].set_visible(False)

fig.savefig("matplotlib_basics_example.png", dpi=150)
plt.show()
Line, bar, scatter, and box plots created with Matplotlib
Four Axes arranged in one Figure

6. Plot Data from CSV or Excel

In practical work, pandas can load a table and pass its columns to Matplotlib.

Create a line chart from a CSV file
import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv("sales.csv")

fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(df["month"], df["sales"], marker="o")
ax.set_xlabel("Month")
ax.set_ylabel("Sales")
ax.set_title("Monthly Sales")

fig.savefig("sales.png", dpi=150, bbox_inches="tight")
plt.show()

Use pd.read_excel("sales.xlsx") for an Excel workbook.

Install pandas and Excel support
python -m pip install pandas openpyxl
Extra spaces in headers, text mixed into numeric columns, and unsorted dates are common causes of confusing charts. Check df.head() and df.dtypes before plotting.

7. Customize Titles, Colors, Legends, and Grids

Basic styling
fig, ax = plt.subplots(figsize=(8, 4.5))

ax.plot(
    month,
    sales,
    color="#be3455",
    linewidth=2,
    marker="o",
    label="Sales"
)
ax.set_title("Monthly Sales", fontsize=16)
ax.set_xlabel("Month")
ax.set_ylabel("Sales")
ax.set_ylim(0, 250)
ax.grid(axis="y", linestyle="--", alpha=0.35)
ax.legend()

fig.tight_layout()

For repeated designs, style sheets and rcParams can collect shared defaults instead of repeating every option in each script.

8. Save a Chart as PNG, SVG, or PDF

Export a Figure
fig.savefig("chart.png", dpi=300, bbox_inches="tight")
fig.savefig("chart.svg", bbox_inches="tight")
fig.savefig("chart.pdf", bbox_inches="tight")
  • PNG: convenient for websites, email, and ordinary documents
  • SVG: scalable and useful for web or later editing
  • PDF: useful for print, papers, and reports

dpi controls raster resolution, while bbox_inches="tight" helps prevent labels from being clipped. Saving before plt.show() also avoids blank output in some environments.

9. Fix Missing or Square Font Characters

If a label appears as empty squares, the required font may be missing or Matplotlib may not be selecting it.

Select an installed font
import matplotlib.pyplot as plt

plt.rcParams["font.family"] = "Noto Sans CJK JP"
plt.rcParams["axes.unicode_minus"] = False
Font names differ across computers and servers. Confirm that the named font is actually installed in the environment that renders the chart.

10. Common Problems

ProblemWhat to check
No chart appearsAdd plt.show() and check whether the environment has a usable display backend
Labels overlap or are clippedTry layout="constrained", fig.tight_layout(), or bbox_inches="tight"
A line jumps backwardSort the X values, especially dates, before plotting
Numeric data plots incorrectlyUse df.dtypes to check whether the column was read as text
Characters appear as squaresInstall the needed font and select its exact family name
Memory grows during batch outputCall plt.close(fig) after saving each Figure

11. Matplotlib, Excel, or Sakura Chart?

ToolBest suited toTradeoff
Matplotlib Automation, detailed styling, batch output, and integration with Python analysis Requires code and a Python environment
Excel Cell-level calculation, formulas, pivoting, and visual editing Repeated chart formatting can take many manual steps
Sakura Chart Pasting an Excel table and quickly selecting columns, colors, and a standard chart without code Does not provide Matplotlib's code-level freedom

Matplotlib is the strongest option when automation and reproducibility matter. If you simply need to turn an existing table into a chart without installing Python, a table-first web tool can be faster.

Create a Chart Without Code

With Sakura Chart, paste a table from Excel or a spreadsheet, choose the chart type, columns, and colors, and generate a bar, line, scatter, box, or pie chart in your browser.

Try Sakura Chart for free

12. Summary

  • Matplotlib creates many types of charts from Python code
  • fig, ax = plt.subplots() provides a clear structure for reusable plots
  • Choose plot, bar, scatter, hist, or boxplot based on the question
  • savefig exports a Figure as PNG, SVG, PDF, and other formats
  • Use Matplotlib for automation and flexibility; use Excel or Sakura Chart for a table-first workflow

Official Resources