0% found this document useful (0 votes)
11 views8 pages

Matplotlib Line Styles Overview

Uploaded by

sksigmaman
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views8 pages

Matplotlib Line Styles Overview

Uploaded by

sksigmaman
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

K.M.G.

COLLEGE OF ARTS & SCIENCE(AUTONOMOUS)


DEPARTMENT OF DATA SCIENCE
E-NOTES : FUNDAMENTALS OF DATA SCIENCE

Unit-5
Plotting and visualization:
A brief matplotlib API primer, figures and subplot, color, markers and line styles, ticks,
labels and legends, Annotations and drawing on a subplot, saving plot to file, plotting functions
in pandas, line plot, bar plots, histograms and density plots, and scatter plots.
---------------------------------------------------------------------------------------------------------------------
DATA VISUALIZATION:

Data visualization is the graphical representation of data. It involves transforming data into
visual elements like charts, graphs, and maps to make it easier to understand, analyze, and
communicate.

By converting raw data into visual formats, data visualization helps people identify patterns,
trends, and relationships that might be difficult to discern from numerical data alone. It's a
powerful tool for:

 Understanding complex data: Visualizations can simplify complex datasets, making


them more accessible to a wider audience.
 Identifying trends and patterns: Visual representations can quickly highlight trends,
outliers, and correlations.
 Communicating findings effectively: Visualizations can convey information more
effectively than text or tables, especially to non-technical audiences.
 Making data-driven decisions: By understanding data through visualizations, decision-
makers can make informed choices based on evidence.

Common data visualization techniques include:

 Line charts: Show trends over time.


 Bar charts: Compare values across categories.
 Scatter plots: Display relationships between two variables.
 Histograms: Show the distribution of a single variable.
 Pie charts: Represent proportions of a whole.
 Maps: Visualize geographic data.
 Heatmaps: Show the intensity of data across a grid.
 Network diagrams: Represent connections between entities.

Data visualization plays a key role in data science and analysis. It enables us to grasp datasets
by representing them. Matplotlib, a known Python library offers a range of tools, for
generating informative and visually appealing plots and charts. One outstanding feature of

1
K.M.G. COLLEGE OF ARTS & SCIENCE(AUTONOMOUS)
DEPARTMENT OF DATA SCIENCE
E-NOTES : FUNDAMENTALS OF DATA SCIENCE

Matplotlib is its user-versatile interface called Pyplot API, which simplifies the process of
creating plots.
Define Matplotlib.
Matplotlib is a python library it used to visualizations in python. It’s used for creating
static, animated, and interaction visualization in python.
Which library is used for Matplotlib?
o Numpy library and is a core part of the spicy short –a group of scientific
computing tools for python.
o A panda is a library used by matplotlib mainly for data manipulation and
analysis.
Simple example coding for matplotlib:
Import [Link] as plt
Figures and Subplots in Matplotlib
Figures in Matplotlib are the top-level containers for all plot elements, such as axes, lines, and
text. A figure can contain multiple subplots.
Subplots are individual plotting areas within a figure. They are typically arranged in a grid-like
structure.
import [Link] as plt
fig, ax = [Link]()
[Link]([1, 2, 3], [4, 5, 6])
[Link]()

2
K.M.G. COLLEGE OF ARTS & SCIENCE(AUTONOMOUS)
DEPARTMENT OF DATA SCIENCE
E-NOTES : FUNDAMENTALS OF DATA SCIENCE

Colors

 Basic Colors: You can specify colors by name (e.g., 'red', 'blue', 'green').
 Hex Codes: You can use hex codes for colors (e.g., '#FF5733' for a specific shade of
orange).
 Shorthand Notations: Some colors have shorthand notations (e.g., 'r' for red, 'g' for
green, 'b' for blue).
 Example:
[Link](x, y, color='red') # Line will be red
[Link](x, y, color='#FF5733') # Line will be a specific orange shade

Markers

 Purpose: Markers highlight individual data points on a plot.


 Common Marker Styles:
o '.': Point
o 'o': Circle
o '^': Triangle up
o 's': Square
o 'x': Cross
 Example:
[Link](x, y, marker='o') # Circle markers at each data point
[Link](x, y, marker='x') # Cross markers at each data point

Line Styles

 Purpose: Line styles determine the appearance of lines in plots.


 Common Line Styles:
o '-': Solid line
o '--': Dashed line
o '-.': Dash-dot line
o ':': Dotted line
[Link](x, y, linestyle='--') # Dashed line
[Link](x, y, linestyle='-.') # Dash-dot line

Combining Colors, Markers, and Line Styles

 You can combine all three in a single plot command:


[Link](x, y, color='green', marker='o', linestyle='--') # Green dashed line with circle
markers

3
K.M.G. COLLEGE OF ARTS & SCIENCE(AUTONOMOUS)
DEPARTMENT OF DATA SCIENCE
E-NOTES : FUNDAMENTALS OF DATA SCIENCE

 Shorthand Notation: You can use a single string to combine them (e.g., 'go--' for a green
dashed line with circle markers):
[Link](x, y, 'go--') # Equivalent to color='green', marker='o', linestyle='--'

Ticks

 Purpose: Ticks are the markers along the axes that indicate data values.
 Customizing Ticks:
o [Link]() and [Link](): Set custom tick positions and labels on the x-axis and
y-axis.
o Example:
[Link]([0, 1, 2, 3], ['A', 'B', 'C', 'D']) # Custom labels on the x-axis
[Link]([10, 20, 30, 40], ['Low', 'Medium', 'High', 'Very High']) # Custom
labels on the y-axis

 Rotating Ticks: Rotate tick labels for better readability.


[Link](rotation=45) # Rotate x-axis labels by 45 degrees

Labels

 Purpose: Labels describe the data being plotted on each axis.


 Adding Labels:
o [Link](): Adds a label to the x-axis.
o [Link](): Adds a label to the y-axis.
o Example:
[Link]('Time (hours)') # Label for x-axis
[Link]('Temperature (°C)') # Label for y-axis

 Font Size and Style: You can customize the font size and style of the labels.
[Link]('Time (hours)', fontsize=14, fontweight='bold')
[Link]('Temperature (°C)', fontsize=14, fontstyle='italic')

Legends

 Purpose: Legends describe the different data series or categories in the plot.
 Adding a Legend:
o [Link](): Adds a legend to the plot. The legend labels are usually taken from
the label argument in the plot() function.
o Example:
[Link](x1, y1, label='Dataset 1')

4
K.M.G. COLLEGE OF ARTS & SCIENCE(AUTONOMOUS)
DEPARTMENT OF DATA SCIENCE
E-NOTES : FUNDAMENTALS OF DATA SCIENCE

[Link](x2, y2, label='Dataset 2')


[Link]() # Add a legend to distinguish between the datasets

 Customizing the Legend:


o Location: Control where the legend appears (e.g., 'upper right', 'lower left').
[Link](loc='upper left')
Font Size: Adjust the size of the legend text.
[Link](fontsize='large')

o Title: Add a title to the legend.


[Link](title='Legend Title')

Annotations

 Purpose: Annotations are used to add text labels to specific points in the plot, often to
provide additional information or highlight important data points.
 Adding Annotations:
o [Link](): Adds text to a specific point on the plot.
o Basic Usage:
[Link]('Important Point', xy=(x_value, y_value), xytext=(x_offset, y_offset),
arrowprops=dict(facecolor='black', arrowstyle='->'))

 xy=(x_value, y_value): Coordinates of the point being annotated.


 xytext=(x_offset, y_offset): Position of the text relative to the point.
 arrowprops: Defines the properties of the arrow connecting the text to the
point.
o Example:
[Link](x, y)
[Link]('Peak', xy=(3, 10), xytext=(4, 15),arrowprops=dict(facecolor='blue',
arrowstyle='->'))

Drawing Shapes on a Subplot

 Purpose: Drawing shapes like lines, rectangles, circles, or polygons on a subplot can help
to highlight specific areas or patterns in the data.
 Common Shapes:
o Line: Use [Link](), [Link](), or [Link]() to draw horizontal, vertical, or
diagonal lines.

5
K.M.G. COLLEGE OF ARTS & SCIENCE(AUTONOMOUS)
DEPARTMENT OF DATA SCIENCE
E-NOTES : FUNDAMENTALS OF DATA SCIENCE

[Link](y=5, color='red', linestyle='--') # Horizontal line at y=5


[Link](x=2, color='green', linestyle=':') # Vertical line at x=2

o Rectangle: Use [Link]().add_patch() to add a rectangle.


import [Link] as patches

fig, ax = [Link]()
[Link](x, y)
rect = [Link]((2, 4), 2, 3, linewidth=2, edgecolor='r', facecolor='none')
ax.add_patch(rect) # Adds a rectangle starting at (2,4) with width 2 and height 3

o Circle: Use [Link]().add_patch() with [Link].


circle = [Link]((4, 5), radius=1, linewidth=2,
edgecolor='blue',facecolor='none')

ax.add_patch(circle) # Adds a circle centered at (4,5) with a radius of 1

o Polygon: Use [Link]().add_patch() with [Link].


polygon = [Link]([[1, 2], [3, 4], [5, 1]], closed=True,
edgecolor='purple')
ax.add_patch(polygon) # Adds a polygon with specified vertices

Combining Annotations and Shapes

 You can combine annotations with shapes to provide context or further highlight specific
areas:
fig, ax = [Link]()
[Link](x, y)
ax.add_patch([Link]((2, 4), 2, 3, linewidth=2, edgecolor='r',
facecolor='none'))
[Link]('Highlighted Area', xy=(3, 5.5), xytext=(4,
7),arrowprops=dict(facecolor='black', arrowstyle='->'))

Working with Multiple Subplots

 Adding Annotations and Shapes: You can add annotations and shapes to individual
subplots by referencing the specific Axes object.
fig, (ax1, ax2) = [Link](1, 2)
[Link](x1, y1)

6
K.M.G. COLLEGE OF ARTS & SCIENCE(AUTONOMOUS)
DEPARTMENT OF DATA SCIENCE
E-NOTES : FUNDAMENTALS OF DATA SCIENCE

[Link](x2, y2)
[Link]('Point A', xy=(2, 5), xytext=(3, 7), arrowprops=dict(facecolor='black',
arrowstyle='->'))
ax2.add_patch([Link]((4, 5), radius=0.5, color='green'))
Plotting function in pandas

1. Line Plot (Default)

 A line plot is the default plot type when using .plot() without specifying kind.
 Example:
import [Link] as plt
import pandas as pd

data = {'Year': [2020, 2021, 2022, 2023],


'Sales': [200, 250, 300, 350]}
df = [Link](data)

[Link](x='Year', y='Sales')
[Link]()

2. Bar Plot

 Creates a bar chart, which is useful for comparing quantities across different categories.
 Example:
[Link](kind='bar', x='Year', y='Sales', color='skyblue')
[Link]()

3. Histogram

 A histogram is used to display the distribution of a dataset.


 Example:
df['Sales'].plot(kind='hist', bins=5, color='purple')
[Link]()

4. Scatter Plot

 A scatter plot displays individual data points to show relationships between two
variables.
 Example:
[Link](kind='scatter', x='Year', y='Sales', color='red')
[Link]()

7
K.M.G. COLLEGE OF ARTS & SCIENCE(AUTONOMOUS)
DEPARTMENT OF DATA SCIENCE
E-NOTES : FUNDAMENTALS OF DATA SCIENCE

5. Box Plot

 A box plot (or box-and-whisker plot) shows the distribution of data based on a five-
number summary.
 Example:
[Link](kind='box')
[Link]()

[Link] Chart

 A pie chart shows proportions of a whole. Typically used with a Series or one column of
a DataFrame.
 Example:
df.set_index('Year')['Sales'].plot(kind='pie', autopct='%1.1f%%')
[Link]('') # Remove the default y-label
[Link]()

Common questions

Powered by AI

Annotations in Matplotlib enhance plots by adding explanatory text to specific points, providing additional context or highlighting important data. This can be implemented using the plt.annotate() function, where parameters like 'xy' specify the point of annotation, 'xytext' determines the text position relative to the data point, and 'arrowprops' specify the arrow connecting the text to the point. An example is plt.annotate('Peak', xy=(3, 10), xytext=(4, 15), arrowprops=dict(facecolor='blue', arrowstyle='->')), which labels a peak on the plot with an arrow pointing to it .

Colors in Matplotlib are used to distinguish different elements of the graph for clarity and visual appeal. They can be specified by names (e.g., 'red'), hex codes (e.g., '#FF5733'), or shorthand notations (e.g., 'r' for red). Colors can be applied to lines, markers, or areas within graphs using commands such as plt.plot(x, y, color='red') for a red line or plt.plot(x, y, color='#FF5733') for an orange line .

Figures and subplots in Matplotlib allow for complex data visualization by organizing multiple plots within a single window, enabling comparisons and detailed analysis. A 'Figure' acts as the top-level container that can hold one or more 'Axes' or 'Subplots'. Subplots are individual plotting areas typically arranged in a grid structure. The creation of figures and subplots involves using commands like plt.subplots(), which returns a figure and axes object to be used for plotting data in different configurations .

To illustrate the distribution of a variable in data visualization, histograms and density plots are commonly used. A histogram displays the distribution by dividing data into bins and displaying frequencies as bars. Density plots, on the other hand, provide a smoothed interpretation of the distribution using a continuous line. While histograms give a clear numerical representation by counting occurrences, density plots are more suited for understanding the overall distribution shape and trends without binning artifacts .

Plotting functions in Pandas simplify data analysis by offering easy-to-use abstractions over Matplotlib to generate common types of plots rapidly, such as line plots, bar charts, and scatter plots. Examples include: df.plot(x='Year', y='Sales') for line plots showing trends over time, df.plot(kind='bar', x='Year', y='Sales') for comparing quantities in categories, and df.plot(kind='scatter', x='Year', y='Sales') for examining variable relationships .

Scatter plots visualize the relationships between two continuous variables by displaying individual data points, helping to identify patterns or correlations. Color can differentiate data series or highlight specific subsets within the plot, aiding in understanding multi-dimensional relationships. For instance, using different colors to signify categories or data segments allows for immediate visual separation of groups, which can reveal trends or clusters, enhancing the interpretive value of the scatter plot .

Ticks and labels in data plots provide reference points and contextual information on the axes. Customization can improve clarity by aligning labels with significant data intervals and enhancing readability. Ticks can be adjusted using plt.xticks() and plt.yticks() to set positions and labels, while rotation can be applied for readability (e.g., plt.xticks(rotation=45)). Labels on axes are added using plt.xlabel() and plt.ylabel() for descriptive context, which can also be styled for font size and weight .

Legends in Matplotlib describe data series or categories, aiding understandability by differentiating between multiple datasets in a plot. They can be customized in terms of location using the 'loc' parameter (e.g., plt.legend(loc='upper left')), font size, and by adding a title with plt.legend(title='Legend Title'). Legends typically derive their labels from the 'label' argument in the plot function .

Markers in Matplotlib are used to highlight individual data points, making it easier to identify specific values on a plot. They can be customized in terms of shape using styles like '.' for point, 'o' for circle, and 'x' for cross. Markers are specified in the plot command by using the 'marker' parameter, such as plt.plot(x, y, marker='o') for circle markers at each data point .

Combining annotations with shapes refines plot focus by simultaneously highlighting areas of interest and providing explanatory text. Shapes can be drawn using objects like Rectangle or Circle with patches, and annotations can describe significance (e.g., highlighting a peak region). This combination can clarify complex areas of the plot, improve visual storytelling, and emphasize key findings. Implementation involves overlaying annotations and shape patches on the Axes object, enhancing depth and context for specific data points .

You might also like