Line Graphs
I. Creating Line Plots
Line graphs are helpful for visualizing how a variable changes over time.
We can create a simple line graph using plt.plot() and display it using plt.show()
plt.plot(data1.x_values, data1.y_values)
plt.show()
To create multiple lines, we add the second plt.plot() before plt.show()
plt.plot(data1.x_values, data1.y_values)
plt.plot(data2.x_values, data2.y_values)
plt.show()
II. Adding text to plots
We we share graph, we must add lables
1. Axes and title lables
- x-axis:
plt.xlable(x_values) - y-axis:
plt.ylable(y_values) - plot-title:
plt.title(value)
Note:
- The value must be a string and be placed in quotes. If we forget to put the string in quote, we’ll get Syntax Error
- We can add these lables at any order before
plt.show()
For example
plt.xlable("Months")
plt.ylable("USD")
plt.title("Sales")
plt.show()
2. Legends
If we have multiple lines in the same graph, we can label them by using the command plt.legend()
- First step: Add
lablein eachplt.plot() - Add function
plt.legend()
For example
plt.plot(vietnam.months, vietnam.sales, lable="Vietnam")
plt.plot(thailand.months, thailand.sales, lable="Thailand")
plt.plot(laos.months, laos.sales, lable="Laos")
plt.legend()
3. Arbitrary text
If we only want to add quick text, we can use plt.text().
This function takes 3 arguments
- xcoord: x-coordinate we want for the text
- ycoord: y-coordinate we want for the text
- The text
plt.text(xcoord, ycoord, "Text Message")
For example, if we want to note at the coordinate (3,4). We can use
plt.text(3, 4, "Sales increase")
4. Modifying text
- Change font size
plt.title("Sales", fontsize=25)
- Change font color
plt.legend(color = "blue")
Check Web colors on Wikipedia.
III. Adding Styles to plots
1. Changing line color
We can change line color using keyword color
plt.plot(x, y1, color="tomato")
plt.plot(x, y2, color="organge")
2. Changing line width
We can change line width using keyword linewidth
plt.plot(x, y1, linewidth=1)
plt.plot(x, y2, linewidth=2)
3. Changing line style
We can change line width using keyword linestyle
For example, we can change linestyle to dotted (’:’), dashed(’–’), or no line (’')
plt.plot(x, y1, linestyle='-')
plt.plot(x, y2, linestyle='--')
plt.plot(x, y3, linestyle='-.')
plt.plot(x, y4, linestyle=':')
4. Adding markers
We can add markers width using keyword marker
For example, we can change the marker to circle (‘o’), diamond(’d’), star (’*’), or square (’s’).
plt.plot(x, y1, marker='x')
plt.plot(x, y2, marker='s')
plt.plot(x, y3, marker='o')
plt.plot(x, y4, marker='d')
plt.plot(x, y5, marker='*')
plt.plot(x, y6, marker='h')
5. Setting a style
Changing the plotting style is a fast way to change the entire look of your plot without having to update individual colors or line styles. Some popular styles include:
- ‘fivethirtyeight’ - Based on the color scheme of the popular website
- ‘grayscale’ - Great for when you don’t have a color printer!
- ‘seaborn’ - Based on another Python visualization library
- ‘classic’ - The default color scheme for Matplotlib
View all styles by typing print(plt.style.available) in the console.
plt.style.use('fivethirtyeight')
plt.style.use('ggplot')
plt.style.use('seaborn')
plt.style.use('default')
IV. Zoom
To zoom, we can use plt.axis() with a list of input containing:
- The minimum x-value displayed
- The maximum x-value displayed
- The minimum y-value displayed
- The maximum y-value displayed
For example, to display a plot from x=0 to x=2 and from y=3 to y=5, we write
plt.axis([0, 2, 3, 5])
V. Creating subplot
We can create subplots using .subplot()
The command plt.subplot() needs three arguments:
- The number of rows of subplots
- The number of columns of subplots
- The index of the subplot we want to create
# Data sets
x = [1, 2, 3, 4]
y = [1, 2, 3, 4]
# First Subplot
plt.subplot(1, 2, 1) # a figure that has 1 row with 2 columns
plt.plot(x, y, color='blue')
plt.title('First Subplot')
# Second Subplot
plt.subplot(1, 2, 2)
plt.plot(x, y, color='red')
plt.title('Second Subplot')
# Display both subplots
plt.show()
We can customize the spacing between subplots using plt.subplots_adjust()
.subplots_adjust() has some keyword arguments that can move your plots within the figure:
- left: the left-side margin, with a default of 0.125. Increase this number to make room for a y-axis label
- right: the right-side margin, with a default of 0.9. Increase this to make more room for the figure, or decrease it to make room for a legend
- bottom: the bottom margin, with a default of 0.1. Increase this to make room for tick mark labels or an x-axis label
- top: the top margin, with a default of 0.9
- wspace: the horizontal space between adjacent subplots, with a default of 0.2
- hspace: the vertical space between adjacent subplots, with a default of 0.2
For example, to adjust both the top and the hspace:
plt.subplots_adjust(top=0.98, hspace=0.3)
Example 1
Create a figure that has two rows of subplots
- one subplot in the top row
- two subplots in the bottom row
Increase the spacing between horizontal subplots to 0.3 and the bottom margin to 0.25.
from matplotlib import pyplot as plt
x = range(7)
straight_line = [0, 1, 2, 3, 4, 5, 6]
parabola = [0, 1, 4, 9, 16, 25, 36]
cubic = [0, 1, 8, 27, 64, 125, 216]
# Subplot 1
plt.subplot(2, 1, 1)
plt.plot(x, straight_line)
# Subplot 2
plt.subplot(2, 2, 3)
plt.plot(x, parabola)
# Subplot 3
plt.subplot(2, 2, 4)
plt.plot(x, cubic)
plt.subplots_adjust(wspace=0.3, bottom=0.25)
plt.show()
Example 2
from matplotlib import pyplot as plt
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
visits_per_month = [9695, 7909, 10831, 12942, 12495, 16794, 14161, 12762, 12777, 12439, 10309, 8724]
# numbers of key limes sold each month
key_limes_per_month = [92.0, 109.0, 124.0, 70.0, 101.0, 79.0, 106.0, 101.0, 103.0, 90.0, 102.0, 106.0]
# Create a figure of width 12 and height 8
plt.figure(figsize=(12,8))
# Create a left subplot
ax1 = plt.subplot(1,2,1)
x_values = range(len(months))
plt.plot(x_values, visits_per_month, marker='o')
plt.xlabel("month")
plt.ylabel("visitors")
ax1.set_xticks(x_values)
ax1.set_xticklabels(months)
plt.title("Visitors per month")
# Create a right subplot
ax2 = plt.subplot(1,2,2)
plt.plot(x_values, key_limes_per_month, marker='x', color="orange")
plt.xlabel("month")
plt.ylabel("limes sold")
ax2.set_xticks(x_values)
ax2.set_xticklabels(months)
plt.title("Limes sold per month")
plt.show()
# Save figure
plt.savefig("visit_sublime.png")
VI. X-ticks and Y-ticks
We can change the x-tick and y-tick marks with ax.set_xticks() and ax.set_yticks().
These functions accept an array of values representing tick mark positions.