Creating and Customizing Bar Charts with Matplotlib in Python

目次

Overview

This is a guide for creating customized bar charts using Matplotlib, a data visualization library for Python. We will explain how to control major parameters like bar colors, border thickness, width, and axis tick labels to create professional-looking graphs.

Specifications

  • Input: List of category names (strings), list of numerical data (integers), and style settings (colors, widths, etc.).
  • Output: Graph drawn in a window (plt.show()) or saved as an image file.
  • Requirements: The matplotlib library must be installed.

Minimum Usage

import matplotlib.pyplot as plt

# Minimal data
categories = ["Item 1", "Item 2", "Item 3"]
values = [100, 150, 80]

# Draw graph
fig, ax = plt.subplots()
ax.bar(categories, values)
plt.show()

Full Code Example

The following code demonstrates a complete example with detailed settings for bar width, color, borders, and axis labels.

import matplotlib.pyplot as plt

def main():
    # 1. Prepare data (e.g., scores for each department)
    departments = ["Sales", "Marketing", "Develop", "HR", "Support"]
    scores = [85, 62, 95, 70, 78]

    # Define X-axis coordinate positions (0, 1, 2...)
    x_positions = range(len(departments))

    # 2. Generate Figure and Axes
    # Use figsize to specify the image size (width in inches, height in inches)
    fig, ax = plt.subplots(figsize=(8, 5))

    # 3. Draw bar chart and apply styles
    # Specify colors, borders, and widths in arguments
    ax.bar(
        x=x_positions,          # X-axis positions
        height=scores,          # Height of bars (data values)
        width=0.6,              # Width of bars (1.0 means no gap)
        bottom=0,               # Starting position on the Y-axis
        color='#66b3ff',        # Fill color (Hex code)
        edgecolor='#003366',    # Border color
        linewidth=2,            # Border thickness
        align='center'          # Tick alignment ('center' or 'edge')
    )

    # 4. Set axis ticks and labels
    # Specify numerical positions for X-axis
    ax.set_xticks(x_positions)
    # Apply labels (department names) corresponding to the positions
    ax.set_xticklabels(departments)

    # Other visual adjustments (title and labels)
    ax.set_title("Department Performance Scores")
    ax.set_xlabel("Department")
    ax.set_ylabel("Score")
    
    # Display grid lines (Y-axis only, dashed, with transparency)
    ax.grid(axis='y', linestyle='--', alpha=0.7)

    # 5. Execute drawing
    plt.show()

if __name__ == "__main__":
    main()

Customization Points

You can adjust the graph appearance by changing parameters in the ax.bar() method and other Axes object methods.

Main Arguments for ax.bar()

ParameterDescriptionExample
xPosition on the X-axis (Coordinates). Required.[0, 1, 2]
heightHeight of the bars (Data values). Required.[10, 20, 30]
widthWidth of the bars. Default is 0.8.0.5
bottomY-coordinate of the bar base. Used for stacked charts.0 (Default)
colorFill color of the bars. Name or Hex code.'blue', '#FF5733'
edgecolorColor of the bar borders.'black'
linewidthThickness of the borders (in points).2.0
alignAlignment of the bar relative to the tick.'center', 'edge'

Axis Configuration Methods (Axes Object)

MethodDescriptionPurpose
set_xticksSpecifies the numerical positions for axis ticks.Aligns ticks with the center of bars.
set_xticklabelsSpecifies labels (strings) for the tick positions.Replaces numbers with category names.
  • Changing Colors: You can use color names like 'skyblue' or 'salmon', as well as Hex codes like '#RRGGBB'.
  • Emphasizing Borders: If the background is white, light-colored bars might be hard to see. Set edgecolor and linewidth to improve visibility.

Important Notes

  • Japanese Character Issues: By default, Matplotlib may display square boxes instead of Japanese characters. We recommend using English or setting up specific fonts for Japanese support.
  • Element Count Mismatch: The length of the x (positions) and height (values) lists must be the same. If they differ, a ValueError will occur.
  • Align Setting: If you set align='edge', the left edge of the bar aligns with the x coordinate, which may look offset from the labels. Usually, the default 'center' is preferred.

Variations (Optional)

Horizontal Bar Chart (barh)

A horizontal bar chart is suitable for long category names or ranking displays. Note that some arguments are different, such as using height for bar thickness instead of width.

import matplotlib.pyplot as plt

def create_horizontal_bar():
    labels = ["Long Category Name A", "Long Category Name B", "Long Category Name C"]
    values = [45, 88, 30]
    y_pos = range(len(labels))

    fig, ax = plt.subplots(figsize=(8, 3))

    # Use barh
    ax.barh(
        y=y_pos,
        width=values,       # Pass data values to width
        height=0.5,         # Specify bar thickness in height
        color='lightgreen',
        edgecolor='green'
    )

    ax.set_yticks(y_pos)
    ax.set_yticklabels(labels)
    
    # Adjust X-axis range
    ax.set_xlim(0, 100)

    plt.tight_layout()
    plt.show()

if __name__ == "__main__":
    create_horizontal_bar()

Summary

When creating a bar chart in Matplotlib, you can build high-quality designs by setting the arguments of ax.bar() correctly. Combining set_xticks and set_xticklabels allows you to display any category data clearly on the axes. Adjust the colors and widths to suit your needs for better readability.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次