line graph
A line graph is a chart used to represent the trend of data over time, variables or other continuities. By placing time or such a similar continuous variable on the horizontal axis, the values of data points can be placed on the vertical axis to capture changes in the data over time. Line graphs can be used to compare trends in different variables, easily spotting differences between...
import as plt import numpy as np # Generate data x = (0, 10, 100) y1 = (x) y2 = (x) # Create a drawing window, size 8x6 inches (figsize=(8, 6)) # Plotting line graphs (x, y1, label='sin(x)') (x, y2, label='cos(x)') # Add legend, displayed in the upper right corner (loc='upper right') # Add title and axis labels ('Sin and Cos functions') ('x') ('y') # Display gridlines (True) # Save images in a variety of formats such as PNG, PDF, SVG, etc. ('line_plot.png', dpi=300) # Display image ()
Example results:
Parameter Description:
- (figsize=(8, 6)): creates a drawing window with a size of 8x6 inches.
- (x, y1, label='sin(x)'): plots a line graph, where x and y1 are the x-coordinates and y-coordinates of the data points, and label is the label of the line for display in the legend.
- (loc='upper right'): add a legend, the loc parameter specifies the location of the legend, it can be a string 'upper right' etc. or a number 0~10.
- ('Sin and Cos functions'): add title.
- ('x'): add the x-axis label.
- ('y'): add y-axis label.
- (True): Displays the grid lines.
- ('line_plot.png', dpi=300): save the image to the file line_plot.png, the dpi parameter specifies the output resolution.
histogram
A bar chart is a type of chart used to compare the differences between different groups of data. It shows differences by representing the values of each data group as the height of the bar. A bar chart can be used to compare the number, frequency, or rate of different categories of data and is used to show the relative size of that category of data.
import as plt import numpy as np # Generate data x = ['A', 'B', 'C', 'D', 'E'] y1 = [3, 7, 2, 5, 9] y2 = [5, 2, 6, 3, 1] # Create a drawing window, size 8x6 inches (figsize=(8, 6)) # Plotting bar charts (x, y1, color='lightblue', label='Group 1') (x, y2, color='pink', bottom=y1, label='Group 2') # Add legend, displayed in the upper right corner (loc='upper right') # Add title and axis labels ('Bar Plot') ('Category') ('Value') # Display image ()
Example results:
Parameter Description:
- (x, y1, color='lightblue', label='Group 1'): draws a bar chart. x is a list of categories, y1 is the value corresponding to each category, and label is the label of the group's data, which is used to be displayed in the legend. the color parameter specifies the color of the bar chart.
- (x, y2, color='pink', bottom=y1, label='Group 2'): plots a bar chart of the second group of data, with the bottom parameter specifying the position of the bottom of the group.
- (loc='upper right'): add a legend, the loc parameter specifies the location of the legend, it can be a string 'upper right' etc. or a number 0~10.
- ('Bar Plot'): Adds a title.
- ('Category'): add x-axis label.
- ('Value'): add y-axis label.
bar chart
Histograms are used to show the distribution of data and are often used to analyze characteristics such as skewness and kurtosis of a data set.
import as plt import numpy as np # Generate randomized data (42) data = (size=1000) # Plotting histograms fig, ax = () (data, bins=30, density=True, alpha=0.5, color='blue') # Setting up chart titles and axis labels ax.set_title('Histogram of Random Data', fontsize=16) ax.set_xlabel('Value', fontsize=14) ax.set_ylabel('Frequency', fontsize=14) # Setting Axis Scale Label Size ax.tick_params(axis='both', which='major', labelsize=12) # Show charts ()
Example results:
Parameter Description:
- data: the dataset to be plotted.
- bins: the number of bins in the histogram.
- density: whether to convert frequency to probability density.
- alpha: the transparency of the histogram.
- color: the color of the histogram.
- ax.set_title(): set the chart title.
- ax.set_xlabel(): set the x-axis label.
- ax.set_ylabel(): set the y-axis label.
- ax.tick_params(): set the size of the axis tick labels.
pie chart
Pie charts are used to show how the data is accounted for and are often used to compare the percentages between different categories or sections.
import as plt # Generate data labels = ['A', 'B', 'C', 'D'] sizes = [15, 30, 45, 10] colors = ['red', 'green', 'blue', 'yellow'] # Pie charts drawn fig, ax = () (sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=90) # Set the chart title ax.set_title('Pie Chart of Data', fontsize=16) # Show charts ()
Example results:
Parameter Description:
- labels: category labels for the data.
- sizes: percentage of data.
- colors: the colors of the data.
- autopct: the display format of the duty cycle.
- startangle: the start angle of the pie chart.
- ax.set_title(): set the chart title.
line drawing
A bracket chart is a graph used to compare the distribution of different sets of data. It is used to show the median, upper and lower quartiles, minimum and maximum values of the data and can help us understand the shape, location and dispersion of the data distribution. In a bracket chart, each box represents the 25% to 75% quartile of the data, the median line is the median in each box, and the common line is the minimum and maximum values outside each box.
import as plt # Generate data data = [[3.4, 4.1, 3.8, 2.0], [2.3, 4.5, 1.2, 4.3]] # Create a drawing window, size 8x6 inches (figsize=(8, 6)) # Bracket mapping bp = (data, widths=0.5, patch_artist=True, notch=True) # Set the color and fill of each box plot for patch, color in zip(bp['boxes'], ['lightblue', 'pink']): patch.set_facecolor(color) # Add title and axis labels ('Box Plot') ('Group') ('Data') # Display image ()
Example results:
Parameter Description:
- (data, widths=0.5, patch_artist=True, notch=True): draws the bracketed line graphs. data is a list containing two lists representing two sets of data. the widths parameter specifies the width of each box line graph, the patch_artist parameter specifies that patches are used to fill the box line graphs, and the notch parameter specifies that the scoreboard in the box plot is drawn.
- patch.set_facecolor(color): set the color and padding of each box and line plot. The zip function can pack the two lists into a tuple, and take out the values of the tuple one by one.
- ('Box Plot'): adds a title.
- ('Group'): add x-axis labels.
- ('Data'): add y-axis label.
scatterplot
A scatterplot is a chart used to show the relationship between two variables. Each dot represents a data point whose position is determined by the value of the variable. Scatter plots can be used to find correlations between variables and show any outliers or outliers in the data.
import as plt import numpy as np # Generate data x = (size=100) y = (size=100) # Create a drawing window, size 8x6 inches (figsize=(8, 6)) # Scatterplotting (x, y, s=50, alpha=0.5) # Add title and axis labels ('Scatter Plot') ('x') ('y') # Display image ()
Example results:
Parameter Description:
- (x, y, s=50, alpha=0.5): plots a scatterplot, where x and y are the x and y coordinates of the data points, s specifies the size of the points, and alpha specifies the transparency of the points.
- ('Scatter Plot'): adds a title.
- ('x'): add the x-axis label.
- ('y'): add y-axis label.
box plot (math.)
Box-and-line plots are used to show information such as the distribution of data and outliers, and are often used to compare differences between different data sets.
import as plt import numpy as np # Generate randomized data (42) data = (size=(100, 4), loc=0, scale=1.5) # Plotting box lines fig, ax = () (data, notch=True, sym='o', vert=True, whis=1.5) # Setting up chart titles and axis labels ax.set_title('Boxplot of Random Data', fontsize=16) ax.set_xlabel('Variable', fontsize=14) ax.set_ylabel('Value', fontsize=14) # Setting Axis Scale Label Size ax.tick_params(axis='both', which='major', labelsize=12) # Show charts ()
Example results:
Parameter Description:
- data: the dataset to be plotted.
- notch: whether to draw notch.
- sym: the shape of the marker for the outlier.
- vert: whether or not to plot the boxplot vertically.
- whis: the whisker length of the box plot, standardized to 1.5 times the interquartile spacing.
- ax.set_title(): set the chart title.
- ax.set_xlabel(): set the x-axis label.
- ax.set_ylabel(): set the y-axis label.
- ax.tick_params(): set the size of the axis tick labels.
heat map
Heat maps are used to show relationships and trends between data and are often used to analyze correlations and changes in two-dimensional data.
import as plt import numpy as np # Generate randomized data (42) data = (size=(10, 10), loc=0, scale=1) # Heat mapping fig, ax = () im = (data, cmap='YlOrRd') # Add a color bar cbar = (im, ax=ax) .set_ylabel('Values', rotation=-90, va='bottom') # Add axis labels and titles ax.set_xticks((len(data))) ax.set_yticks((len(data))) ax.set_xticklabels((1, len(data)+1)) ax.set_yticklabels((1, len(data)+1)) ax.set_title('Heatmap of Random Data', fontsize=16) # Show charts ()
Example results:
Parameter Description:
- data: the dataset to be plotted.
- cmap: color map, used to represent the color range of the data size.
- (): Heat mapping.
- .set_ylabel(): set the label of the color bar.
- ax.set_xticks(): set x-axis tick labels.
- ax.set_yticks(): set y-axis tick labels.
- ax.set_xticklabels(): set the label name of the x-axis tick labels.
- ax.set_yticklabels(): set the label name of the y-axis tick labels.
- ax.set_title(): set the chart title.
tree diagram
Tree diagrams are used to show the hierarchy and relationships between data and are often used to analyze issues such as tree structures and organizational architecture.
import as plt # Tree mapping fig, ax = () ('CEO', 1, color='black') ('VP1', 0.8, left=1, color='gray') ('VP2', 0.8, left=1, color='gray') ('Manager1', 0.6, left=1.8, color='gray') ('Manager2', 0.6, left=1.8, color='gray') ('Manager3', 0.6, left=1.8, color='gray') ('Supervisor1', 0.4, left=2.4, color='gray') ('Supervisor2', 0.4, left=2.4, color='gray') ('Supervisor3', 0.4, left=2.4, color='gray') ('Staff1', 0.2, left=3.2, color='gray') ('Staff2', 0.2, left=3.2, color='gray') ('Staff3', 0.2, left=3.2, color='gray') ('Staff4', 0.2, left=3.2, color='gray') # Set up axis labels and titles ax.set_yticks([]) ax.set_xlim(0, 4) ax.set_xlabel('Hierarchy', fontsize=14) ax.set_title('Tree Diagram of Organization', fontsize=16) # Show charts ()
Example results:
- Parameter Description:
- (): Draws a horizontal bar graph.
- ax.set_yticks(): set y-axis tick labels.
- ax.set_xlim(): set the x-axis coordinate range.
- ax.set_xlabel(): set the x-axis label.
- ax.set_title(): set the chart title.
- The article's knowledge points are matched to the official knowledge file, which can be accessed
summarize
to this article on the use of matplotlib in Python to draw all kinds of charts to this article, more related Python matplotlib charting content, please search for my previous posts or continue to browse the following related articles I hope that you will support me in the future more!