📜  matplotlib FiveThirtyEight 水平图 - Python (1)

📅  最后修改于: 2023-12-03 15:17:35.147000             🧑  作者: Mango

Matplotlib FiveThirtyEight Horizontal Bar Chart - Python

Introduction

Matplotlib is a popular data visualization library in Python, and it offers various types of charts and graphs to represent data effectively. One such chart is the horizontal bar chart, which displays data in a horizontal bar format. In this tutorial, we will learn how to create a horizontal bar chart in the style of FiveThirtyEight using Matplotlib.

Prerequisites

Before we begin, make sure you have the following prerequisites installed:

  • Python 3.x
  • Matplotlib

You can install Matplotlib using pip command: pip install matplotlib

Steps to create a horizontal bar chart in Matplotlib FiveThirtyEight style
  1. Import Matplotlib and Numpy libraries.
import matplotlib.pyplot as plt
import numpy as np
  1. Create data for the chart. In this example, we will use data for the number of medals won by the top 5 countries in the 2021 Olympic Games.
countries = ['China', 'United States', 'Japan', 'Australia', 'ROC']
medals = [38, 36, 27, 17, 16]
  1. Define the figure and axis for the chart.
fig, ax = plt.subplots(figsize=(8, 5))
  1. Plot the horizontal bar chart using barh function with the FiveThirtyEight style.
plt.style.use('fivethirtyeight')
ax.barh(countries, medals, color='#008fd5', alpha=0.8)
  1. Add customizations to the chart, such as title, axes labels, and axis limits.
ax.set_title('2021 Olympic Medal Count', fontsize=20)
ax.set_xlabel('Number of Medals')
ax.set_ylabel('Countries')
ax.set_xlim(0, 40)
  1. Add annotations to the chart using the text function.
for i, v in enumerate(medals):
    ax.text(v+0.2, i, str(v), color='#333333', fontsize=14, va='center')
  1. Display the chart using the show function.
plt.show()
Conclusion

In this tutorial, we learned how to create a horizontal bar chart in the style of FiveThirtyEight using Matplotlib. By customizing the chart with different styles, colors, and annotations, we can effectively represent data in a visually appealing way.