Plot Labels and Title
Great! Let's continue improving our plot with some customizing stuff.
Couple more things we can add to our charts are custom labels on the axis and title for the entire plot. To add labels, use .set_xlabel('text')
and .set_ylabel('text')
functions applied to Axes
object to set custom ('text'
) labels on the x-axes or y-axes, respectively.
To set the plot title use the .title('text')
method applied to matplotlib.pyplot
(usually imported as plt
). For example, let's add axes labels and title to the example plot we've built.
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# Import the libraries
import matplotlib.pyplot as plt
import pandas as pd
# Load the data
data = pd.read_csv('https://codefinity-content-media.s3.eu-west-1.amazonaws.com/ed80401e-2684-4bc4-a077-99d13a386ac7/co2.csv', index_col = 0)
# Filter the data
ita = data.loc['Italy']
swe = data.loc['Sweden']
# Create Figure and Axes objects
fig, ax = plt.subplots()
# Initialize lines
ax.plot(ita.index.astype(int), ita.values, label = 'Italy')
ax.plot(swe.index.astype(int), swe.values, label = 'Sweden')
# Add axis labels
ax.set_xlabel('Year')
ax.set_ylabel('CO2 emission level (tonnes per person)')
# Display the legend, title, and plot
plt.legend()
plt.title('CO2 Emission Levels in Italy and Sweden')
plt.show()
1234567891011121314151617181920212223242526# Import the libraries import matplotlib.pyplot as plt import pandas as pd # Load the data data = pd.read_csv('https://codefinity-content-media.s3.eu-west-1.amazonaws.com/ed80401e-2684-4bc4-a077-99d13a386ac7/co2.csv', index_col = 0) # Filter the data ita = data.loc['Italy'] swe = data.loc['Sweden'] # Create Figure and Axes objects fig, ax = plt.subplots() # Initialize lines ax.plot(ita.index.astype(int), ita.values, label = 'Italy') ax.plot(swe.index.astype(int), swe.values, label = 'Sweden') # Add axis labels ax.set_xlabel('Year') ax.set_ylabel('CO2 emission level (tonnes per person)') # Display the legend, title, and plot plt.legend() plt.title('CO2 Emission Levels in Italy and Sweden') plt.show()
Oliko kaikki selvää?
Kiitos palautteestasi!
Osio 1. Luku 8
Kysy tekoälyä
Kysy tekoälyä
Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme