matplotlib_1_chapter1.pdf

chapter 1:

1.1 Introduction

  1. import matplotlib.pyplot as plt
  2. fig, ax = plt.subplots()
  3. ax.plot(seattle_weather["MONTH"], seattle_weather["MLY-TAVG-NORMAL"])
  4. ax.plot(austin_weather["MONTH"], austin_weather["MLY-TAVG-NORMAL"])
  5. plt.show()

1.2 Customizing your plots

ax.plot(seattle_weather["MONTH"], seattle_weather["MLY-PRCP-NORMAL"], marker="o") 
plt.show()

ax.plot(seattle_weather["MONTH"], seattle_weather["MLY-PRCP-NORMAL"], marker="v") 
plt.show()

fig, ax = plt.subplots() 
ax.plot(seattle_weather["MONTH"], seattle_weather["MLY-TAVG-NORMAL"], marker="v", linestyle="--") 
plt.show()

fig, ax = plt.subplots() 
ax.plot(seattle_weather["MONTH"], seattle_weather["MLY-TAVG-NORMAL"], marker="v", linestyle="None") 
plt.show()

fig, ax = plt.subplots() 
ax.plot(seattle_weather["MONTH"], seattle_weather["MLY-TAVG-NORMAL"], marker="v", linestyle="--", color="r") 
plt.show()

ax.set_xlabel("Time (months)")
ax.set_ylabel("Average temperature (Fahrenheit degrees)")
ax.set_title("Weather in Seattle")

1.3 small multiples

fig, ax = plt.subplots(3, 2) 
ax[0, 0].plot(seattle_weather["MONTH"], seattle_weather["MLY-PRCP-NORMAL"], color='b') 
plt.show()
fig, ax = plt.subplots(2, 1) 
ax[0].plot(seattle_weather["MONTH"], seattle_weather["MLY-PRCP-NORMAL"], color='b') 
ax[0].plot(seattle_weather["MONTH"], seattle_weather["MLY-PRCP-25PCTL"], linestyle='--', color='b') 
ax[0].plot(seattle_weather["MONTH"], seattle_weather["MLY-PRCP-75PCTL"], linestyle='--', color='b') 
ax[1].plot(austin_weather["MONTH"], austin_weather["MLY-PRCP-NORMAL"], color='r') 
ax[1].plot(austin_weather["MONTH"], austin_weather["MLY-PRCP-25PCTL"], linestyle='--', color='r') 
ax[1].plot(austin_weather["MONTH"], austin_weather["MLY-PRCP-75PCTL"], linestyle='--', color='r') 
ax[0].set_ylabel("Precipitation (inches)") 
ax[1].set_ylabel("Precipitation (inches)") 
ax[1].set_xlabel("Time (months)") 
plt.show()

# Sharing the y-axis range
fig, ax = plt.subplots(2, 1, sharey=True)

matplotlib_1_chapter2.pdf

chapter 2: Plotting time-series data

1.1 先将时间数据列转为index,使用index作为绘图x轴坐标

import matplotlib.pyplot as plt 
fig, ax = plt.subplots()
ax.plot(climate_change.index, climate_change['co2']) 
ax.set_xlabel('Time') 
ax.set_ylabel('CO2 (ppm)') 
plt.show()

# Zooming in on a decade
sixties = climate_change["1960-01-01":"1969-12-31"]
fig, ax = plt.subplots() 
ax.plot(sixties.index, sixties['co2']) 
ax.set_xlabel('Time') 
ax.set_ylabel('CO2 (ppm)') 
plt.show()

# Zooming in on one year
sixty_nine = climate_change["1969-01-01":"1969-12-31"] 
fig, ax = plt.subplots() 
ax.plot(sixty_nine.index, sixty_nine['co2']) 
ax.set_xlabel('Time') 
ax.set_ylabel('CO2 (ppm)') 
plt.show()

# Plotting two time-series together --- 问题:坐标轴不统一
import pandas as pd 
climate_change = pd.read_csv('climate_change.csv', parse_dates=["date"], index_col="date")
import matplotlib.pyplot as plt 
fig, ax = plt.subplots() 
ax.plot(climate_change.index, climate_change["co2"]) 
ax.plot(climate_change.index, climate_change["relative_temp"]) 
ax.set_xlabel('Time') 
ax.set_ylabel('CO2 (ppm) / Relative temperature') 
plt.show()

# Using twin axes --- 两个图无颜色区分,不明显
fig, ax = plt.subplots() 
ax.plot(climate_change.index, climate_change["co2"]) 
ax.set_xlabel('Time') 
ax.set_ylabel('CO2 (ppm)') 
ax2 = ax.twinx() 
ax2.plot(climate_change.index, climate_change["relative_temp"]) 
ax2.set_ylabel('Relative temperature (Celsius)') 
plt.show()

# Separating variables by color,Coloring the ticks
fig, ax = plt.subplots() 
ax.plot(climate_change.index, climate_change["co2"], color='blue') 
ax.set_xlabel('Time') 
ax.set_ylabel('CO2 (ppm)', color='blue') 
ax.tick_params('y', colors='blue') 
ax2 = ax.twinx() 
ax2.plot(climate_change.index, climate_change["relative_temp"], color='red') 
ax2.set_ylabel('Relative temperature (Celsius)', color='red') 
ax2.tick_params('y', colors='red') 
plt.show()

## 进阶:使用函数封装
def plot_timeseries(axes, x, y, color, xlabel, ylabel): 
    axes.plot(x, y, color=color) 
    axes.set_xlabel(xlabel) 
    axes.set_ylabel(ylabel, color=color) 
    axes.tick_params('y', colors=color)

fig, ax = plt.subplots() 
plot_timeseries(ax, climate_change.index, climate_change['co2'], 'blue', 'Time', 'CO2 (ppm)') 
ax2 = ax.twinx() 
plot_timeseries(ax2, climate_change.index, climate_change['relative_temp'], 'red', 'Time', 'Relative temperature (Celsius)') 
plt.show()

1.2 Annotating time-series data: .annotate()

ax2.annotate(">1 degree", 
             xy=(pd.Timestamp('2015-10-06'), 1), 
             xytext=(pd.Timestamp('2008-10-06'), -0.2), 
             arrowprops={"arrowstyle":"->", "color":"gray"}
            )

matplotlib_1_chapter3.pdf

chapter 3:

1.1 bar chart

medals = pd.read_csv('medals_by_country_2016.csv', index_col=0) 
fig, ax = plt.subplots() 
ax.bar(medals.index, medals["Gold"]) 
plt.show()

# rotate the tick labels
fig, ax = plt.subplots() 
ax.bar(medals.index, medals["Gold"]) 
ax.set_xticklabels(medals.index, rotation=90) 
ax.set_ylabel("Number of medals") 
plt.show()

# visualizing the other medals
fig, ax = plt.subplots 
ax.bar(medals.index, medals["Gold"]) 
ax.bar(medals.index, medals["Silver"], bottom=medals["Gold"]) 
ax.bar(medals.index, medals["Bronze"], bottom=medals["Gold"] + medals["Silver"]) 
ax.set_xticklabels(medals.index, rotation=90) 
ax.set_ylabel("Number of medals") 
plt.show()

# Adding a legend
fig, ax = plt.subplots() 
ax.bar(medals.index, medals["Gold"], label="Gold") 
ax.bar(medals.index, medals["Silver"], bottom=medals["Gold"], label="Silver") 
ax.bar(medals.index, medals["Bronze"], bottom=medals["Gold"] + medals["Silver"], label="Bronze") 
ax.set_xticklabels(medals.index, rotation=90) 
ax.set_ylabel("Number of medals") 
ax.legend() 
plt.show()

1.2 histograms

fig, ax = plt.subplots() 
ax.hist(mens_rowing["Height"]) 
ax.hist(mens_gymnastic["Height"]) 
ax.set_xlabel("Height (cm)") 
ax.set_ylabel("# of observations") 
plt.show()

# Adding Labels
ax.hist(mens_rowing["Height"], label="Rowing") 
ax.hist(mens_gymnastic["Height"], label="Gymnastics") 
ax.set_xlabel("Height (cm)") 
ax.set_ylabel("# of observations") 
ax.legend() 
plt.show()

# setting the number of bins
ax.hist(mens_rowing["Height"], label="Rowing", bins=5) 
ax.hist(mens_gymnastic["Height"], label="Gymnastics", bins=5) 
ax.set_xlabel("Height (cm)") 
ax.set_ylabel("# of observations") 
ax.legend() 
plt.show()

# setting bin boundaries
ax.hist(mens_rowing["Height"], label="Rowing", bins=[150, 160, 170, 180, 190, 200, 210]) 
ax.hist(mens_gymnastic["Height"], label="Gymnastics", bins=[150, 160, 170, 180, 190, 200, 210]) 
ax.set_xlabel("Height (cm)") 
ax.set_ylabel("# of observations") 
ax.legend() 
plt.show()

# transparency: histtype="step"
ax.hist(mens_rowing["Height"], label="Rowing", bins=[150, 160, 170, 180, 190, 200, 210], histtype="step") 
ax.hist(mens_gymnastic["Height"], label="Gymnastics", bins=[150, 160, 170, 180, 190, 200, 210], histtype="step") 
ax.set_xlabel("Height (cm)") 
ax.set_ylabel("# of observations") 
ax.legend() 
plt.show()

1.3 Statistical plotting

  • Adding error bars to bar charts: 设置yerr参数

    fig, ax = plt.subplots() 
    ax.bar("Rowing", mens_rowing["Height"].mean(), yerr=mens_rowing["Height"].std()) 
    ax.bar("Gymnastics", mens_gymnastics["Height"].mean(), yerr=mens_gymnastics["Height"].std()) 
    ax.set_ylabel("Height (cm)") 
    plt.show()
    
  • Adding error bars to plots: .errorbar()

    fig, ax = plt.subplots() 
    ax.errorbar(seattle_weather["MONTH"], seattle_weather["MLY-TAVG-NORMAL"], yerr=seattle_weather["MLY-TAVG-STDDEV"]) 
    ax.errorbar(austin_weather["MONTH"], austin_weather["MLY-TAVG-NORMAL"], yerr=austin_weather["MLY-TAVG-STDDEV"]) 
    ax.set_ylabel("Temperature (Fahrenheit)") 
    plt.show()
    
  • Adding boxplots

    fig, ax = plt.subplots() 
    ax.boxplot([mens_rowing["Height"], mens_gymnastics["Height"]]) 
    ax.set_xticklabels(["Rowing", "Gymnastics"]) 
    ax.set_ylabel("Height (cm)") 
    plt.show()
    

    1.4 scatter plots

    ```python fig, ax = plt.subplots() ax.scatter(climate_change[“co2”], climate_change[“relative_temp”]) ax.set_xlabel(“CO2 (ppm)”) ax.set_ylabel(“Relative temperature (Celsius)”) plt.show()

Customizing scatter plots

eighties = climate_change[“1980-01-01”:”1989-12-31”] nineties = climate_change[“1990-01-01”:”1999-12-31”] fig, ax = plt.subplots() ax.scatter(eighties[“co2”], eighties[“relative_temp”], color=”red”, label=”eighties”) ax.scatter(nineties[“co2”], nineties[“relative_temp”], color=”blue”, label=”nineties”) ax.legend() ax.set_xlabel(“CO2 (ppm)”) ax.set_ylabel(“Relative temperature (Celsius)”) plt.show()

Encoding a third variable by color

fig, ax = plt.subplots() ax.scatter(climate_change[“co2”], climate_change[“relative_temp”], c=climate_change.index) ax.set_xlabel(“CO2 (ppm)”) ax.set_ylabel(“Relative temperature (Celsius)”) plt.show()



[matplotlib_1_chapter4.pdf](https://www.yuque.com/attachments/yuque/0/2022/pdf/26718834/1648864919298-b818d6ad-5e9f-4e0f-a9fc-74d2428035c9.pdf)
<a name="JsJH9"></a>
# chapter4
<a name="vYOLY"></a>
## 1.1 changing style
[https://matplotlib.org/stable/gallery/style_sheets/style_sheets_reference.html](https://matplotlib.org/stable/gallery/style_sheets/style_sheets_reference.html)
```python
plt.style.use("ggplot")
plt.style.use("default")
plt.style.use("bmh")
plt.style.use("seaborn-colorblind")

1.2 save figures

fig.savefig("gold_medals.png")
fig.savefig("gold_medals.jpg")
fig.savefig("gold_medals.jpg", quality=50)
fig.savefig("gold_medals.svg")
fig.savefig("gold_medals.png", dpi=300)
fig.set_size_inches([5, 3])
fig.set_size_inches([3, 5])

1.3 Automating figures from data

sports = summer_2016_medals["Sport"].unique()
fig, ax = plt.subplots() 
for sport in sports: 
    sport_df = summer_2016_medals[summer_2016_medals["Sport"] == sport] 
    ax.bar(sport, sport_df["Height"].mean(), yerr=sport_df["Height"].std()) 
ax.set_ylabel("Height (cm)") 
ax.set_xticklabels(sports, rotation=90) 
plt.show()