In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "how to use Matplotlib to draw statistical graphs in Python". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn "how to use Matplotlib to draw statistical charts in Python"!
1.1 Overview
Matplotlib is an Python drawing package that makes it easy to create 2D diagrams from data stored in various data structures, including lists, numpy arrays, and pandas data boxes. Matplotlib uses an object-oriented drawing method. This means that you can build the drawing step by step by adding new elements to the drawing
Two main objects are used in matplotlib drawings:
Figure object: the overall graph space, which can contain one or more subgraphs
Axis object: for each subgraph rendered in the graph space, the figure object can be regarded as the whole drawing canvas, and the axis object can be regarded as one of the subgraphs.
A graph space can hold one or more axis objects, and this structure allows us to create graphics with one or more subgraphs.
Although Matplotlib contains many modules that provide different drawing functions, the most commonly used module is pyplot
Pyplot provides methods that can be used to add different components to drawing objects, including creating individual diagrams as axis objects, that is, subgraphs
Pyplot modules are typically imported using the alias plt, as follows:
# Import pyplotimport matplotlib.pyplot as plt1.2 uses Matplotlib to create images
To create a graph using matplotlib's object-oriented method, first create a graph (fig) and at least one axis (ax) using the subplots () function in the pyplot module.
Fig, ax = plt.subplots ()
Notice that fig and ax are created at the same time by setting fig and ax to equal the output value of the pyplot.subplots () function. Since no other parameters are provided, the result is a graph with an empty graph
# Create figure and one plot (axis object) fig, ax = plt.subplots ()
1.3 change the picture size
Use the figsize parameter to set the width and height of the drawing space
Figsize = (width, height)
# Resize figurefig, ax = plt.subplots (figsize = (10,6)) 1.4 draw multiple subgraphs
Using the object-oriented method of matplotlib, it is easier to create multiple subgraphs in the graph space by creating additional axis objects.
When adding multiple axis objects, it is best to give them different names (such as ax1 and ax2) so that each axis can be easily used separately
Therefore, you need to provide plt.subplots with new parameters for the layout of the graph: (number of rows, number of columns)
Plt.subplots (1,2)
In this example, 1 and 2 represent a layout of 1 row and 2 columns
# Figure with two plotsfig, (ax1, ax2) = plt.subplots (1,2, figsize = (10,6))
On the contrary, (2) represents 2 rows and 1 column pattern distribution
Fig, (ax1, ax2) = plt.subplots (2,1, figsize = (10,6))
Because figsize= is defined, the figure drawing space maintains this size, no matter how many rows or columns are set.
However, you can adjust the number of rows, columns, and figsize to get the desired size
# Figure with two plotsfig, (ax1, ax2) = plt.subplots (2,1, figsize = (12,12))
You can continue to add as many axis objects as needed to create the overall layout of the desired drawing, and continue to resize the drawing as needed
# Figure with three plotsfig, (ax1, ax2, ax3) = plt.subplots (3,1, figsize = (15,15))
One of the main advantages of the Matplotlib object-oriented approach is that each axis is an independent object and can be customized independently of other drawings in the diagram.
2 use Matplotlib to draw custom charts
Earlier in this chapter, you learned how to use the subplot () function in pyplot to create graphics and axis objects (imported using aliases plt):
Fig,ax = plt.subplots ()
Now that you know how to create a basic drawing using matplotlib, you can start adding data to the drawing in the diagram
First import the matplotlib.pyplot module alias plt and create some lists to draw the * average monthly precipitation (inches) of Boulder, Colorado, provided by the National Oceanic and Atmospheric Administration (NOAA).
# Import pyplot import package import matplotlib.pyplot as plt# Monthly average precipitation monthly average precipitation boulder_monthly_precip = [0.70,0.75,1.85,2.02,1.93,1.62,1.84,1.31,1.39,0.84] # Month names for plotting monthly months = ["Jan", "Feb", "Mar", "Apr", "May", "June" "July", "Aug", "Sept", "Oct", "Nov", "Dec"] 2.1 drawing data using Matplotlib
You can add data to your drawing by calling the desired ax object, which is a previously defined axis element:
Fig,ax = plt.subplots ()
By calling the plot () method of the ax object and specifying the following parameters for the x-axis (horizontal axis) and y-axis (vertical axis) of the drawing
Plot (x_axis, y_axis)
In this example, you are adding data from the previously defined list, which is distributed along the x-axis and y-axis.
# Define plot spacefig, ax = plt.subplots (figsize= (10,6)) # Define x and y axesax.plot (months, boulder_monthly_precip) []
Notice that the output shows the object type of the drawing and the unique identifier (memory location)
[]
You can hide this information by calling plt.show () at the end of the code
# Define plot spacefig, ax = plt.subplots (figsize= (10,6)) # Define x and y axesax.plot (months,boulder_monthly_precip) plt.show ()
2.2 naming conventions for Matplotlib Plot objects
The convention in the Python community is to use ax to name axis objects, but this is not the only one
# Define plot space with ax named bobfig, bob = plt.subplots (figsize= (10,6)) # Define x and y axesbob.plot (months,boulder_monthly_precip) plt.show ()
2.3 create different types of Matplotlib diagrams: scatter charts and bar charts
By default, ax.plot creates the drawing as a line graph (which means that all values are connected by continuous lines across the drawing)
You can use the ax object to create:
Scatter plot (using ax.scatter): a single point whose value is displayed as a discontinuous line
Bar chart (using ax.bar): the value is displayed as a bar whose height indicates the value of a specific point
# Define plot spacefig, ax = plt.subplots (figsize= (10,6)) # Create scatter plotax.scatter (months,boulder_monthly_precip) plt.show ()
# Define plot spacefig, ax = plt.subplots (figsize= (10,6)) # Create bar plotax.bar (months,boulder_monthly_precip) plt.show ()
2.4 Custom drawing title and axis label
You can use the title, xlabel, ylabel parameters in the ax.set () method to add drawing titles and labels to the axis, thus customizing and adding more information to the drawing
Ax.set (title = "Plot title here", xlabel = "X axis label here", ylabel = "Y axis label here") # Define plot spacefig, ax = plt.subplots (figsize= (10,6)) # Define x and y axesax.plot (months, boulder_monthly_precip) # Set plot title and axes labelsax.set (title = "Average Monthly Precipitation in Boulder, CO", xlabel = "Month", ylabel = "Precipitation (inches)") plt.show ()
2.5 Custom multiline drawing title and axis label
Create a title and axis label with multiple lines of text using the new line character * *\ ncharacters * between two words
# Define plot spacefig, ax = plt.subplots (figsize= (10,6)) # Define x and y axesax.plot (months, boulder_monthly_precip) # Set plot title and axes labelsax.set (title = "Average Monthly Precipitation\ nBoulder, CO", xlabel = "Month", ylabel = "Precipitation\ n (inches)") plt.show ()
2.6 label rotation
Use the plt.setp function to set parameters for the entire drawing space, such as custom scale labels
In the following example, the ax.get_xticklabels () function controls the scale label of the x-axis, rotation
# Define plot spacefig, ax = plt.subplots (figsize= (10,6)) # Define x and y axesax.plot (months, boulder_monthly_precip) # Set plot title and axes labelsax.set (title = "Average Monthly Precipitation\ nBoulder, CO", xlabel = "Month", ylabel = "Precipitation\ n (inches)") plt.setp (ax.get_xticklabels (), rotation=45) plt.show ()
2.7 Custom broken lines, dot mark shapes
The shape identification of line segments and points can be modified through marker= parameters.
Marker symbolMarker description.point,pixelocirclevtriangle_ downlink ^ uptriangle_right
Visit the Matplotlib documentation for a more list of tag types
# Define plot spacefig, ax = plt.subplots (figsize= (10,6)) # Define x and y axesax.scatter (months, boulder_monthly_precip, marker =',') # pixel# Set plot title and axes labelsax.set (title = "Average Monthly Precipitation\ nBoulder, CO", xlabel = "Month", ylabel = "Precipitation\ n (inches)") plt.show ()
# Define plot spacefig, ax = plt.subplots (figsize= (10,6)) # Define x and y axesax.plot (months, boulder_monthly_precip, marker ='o') # point# Set plot title and axes labelsax.set (title = "Average Monthly Precipitation\ nBoulder, CO", xlabel = "Month", ylabel = "Precipitation\ n (inches)") plt.show ()
2.8 Custom drawing colors
You can customize the drawing color using the color parameter, and some of the basic color options available in matplotlib are as follows:
B: blue g: green r: red c: cyan m: magenta y: yellow k: black w: white
For these basic colors, you can set the color parameter to equal the full name (for example, cyan) or just the key letters shown in the table above (for example, c)
For more colors, visit the matplotlib documentation on colors
# Define plot spacefig, ax = plt.subplots (figsize= (10,6)) # Define x and y axesax.plot (months, boulder_monthly_precip, marker = 'oasis, color=' cyan') # color=c# Set plot title and axes labelsax.set (title = "Average Monthly Precipitation\ nBoulder, CO", xlabel = "Month", ylabel = "Precipitation\ n (inches)") plt.show ()
# Define plot spacefig, ax = plt.subplots (figsize= (10,6)) # Define x and y axesax.scatter (months, boulder_monthly_precip, marker =',', color= 'k') # color=black# Set plot title and axes labelsax.set (title = "Average Monthly Precipitation\ nBoulder, CO", xlabel = "Month", ylabel = "Precipitation\ n (inches)") plt.show ()
# Define plot spacefig, ax = plt.subplots (figsize= (10,6)) # Define x and y axesax.bar (months, boulder_monthly_precip, color = 'darkblue') # Set plot title and axes labelsax.set (title = "Average Monthly Precipitation\ nBoulder, CO", xlabel = "Month", ylabel = "Precipitation\ n (inches)") plt.show ()
2.8 set color transparency
Use the alpha = parameter to adjust the transparency of the color, with a value close to 0.0 for higher transparency
# Define plot spacefig, ax = plt.subplots (figsize= (10,6)) # Define x and y axesax.bar (months, boulder_monthly_precip, color = 'darkblue', alpha = 0.3) # Transparency setting # Set plot title and axes labelsax.set (title = "Average Monthly Precipitation\ nBoulder, CO", xlabel = "Month", ylabel = "Precipitation\ n (inches)") plt.show ()
2.9 customize the color of the bar chart
You can further customize the bar chart by changing the outline color of each bar to blue using the parameter edgeccolor= and specifying a color from the matplotlib color options discussed earlier
# Define plot spacefig, ax = plt.subplots (figsize= (10,6)) # Define x and y axesax.bar (months, boulder_monthly_precip, color = 'cyan', edgecolor =' darkblue') # outline color setting # Set plot title and axes labelsax.set (title = "Average Monthly Precipitation\ nBoulder, CO", xlabel = "Month", ylabel = "Precipitation\ n (inches)") plt.show ()
2.10 customize the color of the scatter chart
When using a scatter chart, you can also use the c and cmap parameters to assign a color to each point based on its data value
The c parameter allows you to specify the sequence of values to be mapped by the color (for example, boulder _ monthly _ precip), while cmap allows you to specify the color mapping used for that sequence.
The following example uses a YlGnBu color map, where the lower values are filled with yellow to green tones, while the higher values are filled with darker and darker blue tones.
To view a list of color map options, visit the matplotlib cmpas document of
# Define plot spacefig, ax = plt.subplots (figsize= (10,6)) # Define x and y axesax.scatter (months, boulder_monthly_precip, c = boulder_monthly_precip, cmap = 'YlGnBu') # Set plot title and axes labelsax.set (title = "Average Monthly Precipitation\ nBoulder, CO", xlabel = "Month", ylabel = "Precipitation\ n (inches)") plt.show ()
2.11 draw the data as multiple graphs
Recalling matplotlib's object-oriented approach, you can easily include multiple drawings in a drawing by creating additional axis objects:
Fig, (ax1, ax2) = plt.subplots (num_rows, num_columns)
Once you have defined fig and two axis objects, you can add data to each axis and define graphics with unique characteristics
In the following example, ax1.bar creates a custom bar chart in the first drawing, while ax2.scatter creates a custom scatter chart in the second drawing
# Define plot spacefig, (ax1, ax2) = plt.subplots (2,1, figsize= (12,12)) # two rows and one column # Define x and y axesax1.bar (months, boulder_monthly_precip, color = 'cyan', edgecolor =' darkblue') # Define x and y axesax2.scatter (months, boulder_monthly_precip, c = boulder_monthly_precip, cmap = 'YlGnBu') plt.show ()
2.12 add title and axis tags to multiple subgraphs
You can continue to add ax1 and ax2, such as title and axis labels for each individual drawing, as you did when you had only one drawing before.
You can use ax1.set () to define elements for the first drawing (bar chart) and ax2.set () to define elements for the second drawing (scatter chart)
# Define plot spacefig, (ax1, ax2) = plt.subplots (2,1, figsize= (12,12)) # Define x and y axesax1.bar (months, boulder_monthly_precip, color = 'cyan', edgecolor =' darkblue') # Set plot title and axes labelsax1.set (title = "Bar Plot of Average Monthly Precipitation", xlabel = "Month", ylabel = "Precipitation\ n (inches)") # Define x and y axesax2.scatter (months, boulder_monthly_precip, c = boulder_monthly_precip, cmap = 'YlGnBu') # Set plot title and axes labelsax2.set (title = "Scatter Plot of Average Monthly Precipitation", xlabel = "Month", ylabel = "Precipitation\ n (inches)") plt.show ()
Now that you have multiple drawings (each with its own label), you can add an overall title to the entire drawing (using the specified font size), using:
Fig.suptitle ("Title text", fontsize = 16)
# Define plot spacefig, (ax1, ax2) = plt.subplots (2,1, figsize= (12,12)) fig.suptitle ("Average Monthly Precipitation for Boulder, CO", fontsize = 16) # Define x and y axesax1.bar (months, boulder_monthly_precip, color = 'cyan', edgecolor =' darkblue') # Set plot title and axes labelsax1.set (title = "Bar Plot", xlabel = "Month", ylabel = "Precipitation\ n (inches)") # Define x and y axesax2.scatter (months, boulder_monthly_precip, c = boulder_monthly_precip, cmap = 'YlGnBu') # Set plot title and axes labelsax2.set (title = "Scatter Plot", xlabel = "Month", ylabel = "Precipitation\ n (inches)") plt.show ()
2.13 Save the Matplotlib drawing as an image file
You can easily save a drawing to an image file, such as .png, using the following command:
Plt.savefig ("path/name-of-file.png")
You can save the latest data. If you do not specify a path for the file, the file will be created in your current working directory folder.
View the Matplotlib document for a list of other file formats used to save drawings
# Define plot spacefig, (ax1, ax2) = plt.subplots (2,1, figsize= (12,12)) fig.suptitle ("Average Monthly Precipitation for Boulder, CO", fontsize = 16) # Define x and y axesax1.bar (months, boulder_monthly_precip, color = 'cyan', edgecolor =' darkblue') # Set plot title and axes labelsax1.set (title = "Bar Plot", xlabel = "Month", ylabel = "Precipitation\ n (inches)") # Define x and y axesax2.scatter (months, boulder_monthly_precip, c = boulder_monthly_precip, cmap = 'YlGnBu') # Set plot title and axes labelsax2.set (title = "Scatter Plot", xlabel = "Month", ylabel = "Precipitation\ n (inches)") plt.savefig ("output/average-monthly-precip-boulder-co.png") plt.show () 2.14 additional resources
More information about color bars color bars
In-depth introduction to matplotlib
3.1Custom x-axis date scale # Import required python packagesimport osimport pandas as pdimport matplotlib.pyplot as pltfrom matplotlib.dates import DateFormatterimport matplotlib.dates as mdatesimport seaborn as snsimport earthpy as et# Date time conversion registrationfrom pandas.plotting import register_matplotlib_convertersregister_matplotlib_converters () # Get the data# data = et.data.get_data ('colorado-flood') # Set working directoryos.chdir (os.path.join (et.io.HOME,' learning') 'python_data_plot')) # Prettier plotting with seabornsns.set (font_scale=1.5) sns.set_style ("whitegrid")
In this section, you will learn how to draw time series using matplotlib in Python
# Read in the datadata_path = "data/precipitation/805325-precip-dailysum-2003-2013.csv" boulder_daily_precip = pd.read_csv (data_path, parse_dates= ['DATE'], # convert the time string in csv to date format na_values= [' 999.99'] Index_col= ['DATE']) boulder_daily_precip.head ()
.dataframe tbody tr th:only-of-type {vertical-align: middle;}
.dataframe tbody tr th {vertical-align: top;}. Dataframe thead th {text-align: right;}
DAILY_PRECIP STATION STATION_NAME ELEVATION LATITUDE LONGITUDE YEAR JULIAN DATE 2003-01-01 0.0 COOP:050843 BOULDER 2 CO US 1650.5 40.03389-105.28111 2003 1 2003-01-05 NaN COOP:050843 BOULDER 2 CO US 1650.5 40.03389-105.28111 5 2003-02-01 0.0 COOP:050843 BOULDER 2 CO US 1650.5 40.03389-105.28111 2003 32-02-02 NaN COOP:050843 BOULDER 2 CO US 1650.5 40. 03389-105.28111 2003 33 2003-02-03 0.4 COOP:050843 BOULDER 2 CO US 1650.5 40.03389-105.28111 2003 34
# Subset the data # extract data between August 15 and October 15 precip_boulder_AugOct = boulder_daily_precip ["2013-08-15": "2013-10-15"] # View first few rows of dataprecip_boulder_AugOct.head ()
.dataframe tbody tr th:only-of-type {vertical-align: middle;}
.dataframe tbody tr th {vertical-align: top;}. Dataframe thead th {text-align: right;}
DAILY_PRECIP STATION STATION_NAME ELEVATION LATITUDE LONGITUDE YEAR JULIAN DATE 2013-08-21 0.1 COOP:050843 BOULDER 2 CO US 1650.5 40.0338-105.2811 2013 2013-08-26 0.1 COOP:050843 BOULDER 2 CO US 1650.5 40.0338-105.2811 2013 238 2013-08-27 0.1 COOP:050843 BOULDER 2 CO US 1650.5 40.0338-105.2811 2013 239 2013-09-01 0.0 COOP:050843 BOULDER 2 CO US 1650 .5 40.0338-105.2811 2013 2013-09-09 0.1 COOP:050843 BOULDER 2 CO US 1650.5 40.0338-105.2811 2013 252
Fig, ax = plt.subplots (figsize= (12,8)) ax.plot (precip_boulder_AugOct.index.values, precip_boulder_AugOct ['DAILY_PRECIP'] .values,'-oaks, color='purple') ax.set (xlabel= "Date", ylabel= "Precipitation (Inches)", title= "Daily Precipitation\ nBoulder" Colorado 2013 ") # Format the xaxis # date formatting for x-axis ax.xaxis.set_major_locator (mdates.WeekdayLocator (interval=2)) ax.xaxis.set_major_formatter (DateFormatter ("% MMI% d ")) plt.show ()
3.2 date formatting for Matplotlib
In matplotlib, you can also use the DateFormatter module to change the date format on the drawing axis
You need to import DateFormatter from matplotlib, and then specify the format to be used by the date DateFormatter using the following syntax:
% Ymur4-digit year% ymuri 2-digit year% m-month% d-day
To implement a custom date:
Define the date format: myFmt = DateFormatter ("% mplash% d"). The date format is month / day, so it looks like this: 10appert 05, which represents October 5th.
Call the set_major_formatter () method:
Ax.xaxis.set_major_formatter (myFmt)
Apply the date format defined above to the drawing space
# Plot the datafig, ax = plt.subplots (figsize= (10Power6)) ax.scatter (precip_boulder_AugOct.index.values, precip_boulder_AugOct ['DAILY_PRECIP'] .values, color='purple') ax.set (xlabel= "Date", ylabel= "Precipitation (Inches)", title= "Daily Precipitation (inches)\ nBoulder, Colorado 2013") # Define the date formatdate_form = DateFormatter ("% mhand% d") ax.xaxis.set_major_formatter (date_form)
3.3 date scale of the X axis
A specific timescale can be added along the x-axis, for example, a large scale can indicate the beginning of each new working week, and a small scale can represent each working day
Function xaxis.set_major_locator () controls the position of the large scale, and function xaxis.set_minor_locator controls the small scale.
# Plot the datafig, ax = plt.subplots (figsize= (10Power6)) ax.scatter (precip_boulder_AugOct.index.values, precip_boulder_AugOct ['DAILY_PRECIP'] .values, color='purple') ax.set (xlabel= "Date", ylabel= "Precipitation (Inches)", title= "Daily Precipitation (inches)\ nBoulder Colorado 2013 ") # define the date format date_form = DateFormatter ("% m interval=1% d ") ax.xaxis.set_major_formatter (date_form) # ensure that the scale is reduced every other week by ax.xaxis.set_major_locator (mdates.WeekdayLocator (interval=1)) # ax.xaxis.set_minor_locator (mdates.DayLocator (1))
At this point, I believe you have a deeper understanding of "how to use Matplotlib to draw statistical charts in Python". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.