Matplots

Matplotlib homepage

Quick start guide from home page


import matplotlib.pyplot as plt

Basics of matplot lib

Search for: Basics of matplot lib

See if this article is better

What are format strings in Matplotlib plot function?

Search for: What are format strings in Matplotlib plot function?

References for Matplotlib API

The api reference to "plot" function

What does * mean as a python function argument?

Search for: What does * mean as a python function argument?


def func(arg1, *args):
    # function body

The asterisk can be used to specify a variable number of arguments in a function definition.

When the function is called, the arguments passed to the function are automatically packed into a tuple and assigned to the variable args.


# Example 1: Defining
***********************
def func(arg1, *args):
    print(arg1)
    print(args)

func(1, 2, 3, 4, 5)

1
(2,3,4,5)

Example 2: Passing
********************
def func(arg1, arg2, arg3):
    print(arg1, arg2, arg3)

my_list = [1, 2, 3]
func(*my_list)

The API reference for pyplot.plot is a good enough resource

What does ** represent in python method arguments?

Search for: What does ** represent in python method arguments?


# *****************************************
# Take in a dictionary as input
# An arbitrary number of inputs
# *****************************************
def greet(**kwargs):
  print(f'{kwargs["greeting"]}, {kwargs["name"]}!')

greet(name='Alice', greeting='Hello')

# *****************************************
# Regular func: named args
# *****************************************
def greet(name, greeting):
  print(f'{greeting}, {name}!')

greet(name='Alice', greeting='Hello')

# You can do this also
args = {'name': 'Alice', 'greeting': 'Hello'}
greet(**args)

**kwargs stand for Keyword Arguments

What are the parsing rules in python for positional, default, optional, and variable arguments?

Search for: What are the parsing rules in python for positional, default, optional, and variable arguments?

1. Positional arguments: These are the required arguments that must be passed to the function in the correct order. When calling a function with positional arguments, you must pass the arguments in the same order as they are defined in the function's signature.

2. Default arguments: These are optional arguments that have a default value specified in the function's signature. If you do not pass a value for a default argument when calling the function, the default value will be used. Default arguments are always after the positional arguments in the function's signature.

3. Optional arguments: These are optional arguments that do not have a default value specified in the function's signature. If you do not pass a value for an optional argument when calling the function, you must use the keyword syntax to specify the argument name. Optional arguments are always after the default arguments in the function's signature.

4. Variable arguments: These are arguments that can be passed to the function in an arbitrary number. There are two types of variable arguments in Python: positional arguments (denoted by a single asterisk (*) in the function's signature) and keyword arguments (denoted by a double asterisk (**) in the function's signature). Variable arguments are always at the end of the function's signature, after all other arguments.


def func(pos1, pos2, def1='default', opt1=None, *args, **kwargs):
  # function body

func(1, 2)  # pos1=1, pos2=2, def1='default', opt1=None, *args=(), **kwargs={}

func(1, 2, opt1='value')  # pos1=1, pos2=2, def1='default', opt1='value', 
  *args=(), **kwargs={}

func(1, 2, def1='new', *range(3), **{'key': 'value'})  # pos1=1, pos2=2, def1='new', 
  opt1=None, *args=(0, 1, 2), **kwargs={'key': 'value'}

Why do some matplot lib functions have their variable positional argument as the very first argument in python?

Search for: Why do some matplot lib functions have their variable positional argument as the very first argument in python?

1. Standard arguments

2. *args arguments

3. **kwargs arguments

The order of variable positional arguments and default arguments in python

Search for: The order of variable positional arguments and default arguments in python

what does a * mean in python method signature?

Search for: what does a * mean in python method signature?

Here is a better explanation from SOF

The * and the / in Python function signatures

Search for: The * and the / in Python function signatures

Here is the full function syntax from python docs

Parameters after ?*? or ?*identifier? are keyword-only parameters and may only be passed used keyword arguments.

If a parameter has a default value, all following parameters up until the ?*? must also have a default value

1. it is an empty position

2. After it must be key words

3. Before it are positional arguments (i think)

4. There can be only one * with or without an identifier

5. postional args, followed by variable position args, and by key value pairs

6. positional args, *, followed by key value pairs

When do you use "*" in a python function signature?

Search for: When do you use "*" in a python function signature?

A better explanation

A Python, Networking, HTTP SME: https://sethmlarson.dev/

In other words...it is forcing a set of parameters to be keyword only

What do square brackets mean in python function signatures?

Search for: What do square brackets mean in python function signatures?

The square brackets are not actually part of the function's syntax; they are simply used to indicate that the greeting argument is optional.

They are not part of the syntax of the function signature, beware

What does three dots in a python signature mean?

Search for: What does three dots in a python signature mean?

Samples from codebasics Youtube guy: Dhaval Patel

what are rcParams in matplot lib?

Search for: what are rcParams in matplot lib?

In Matplotlib, rcParams is a dictionary-like object that stores default configuration settings for Matplotlib. These default values can be modified using the matplotlib.pyplot.rc function.

For example, you can use rcParams to set the default figure size, font size, or color map for all plots in a script. Here is an example of how you can use rcParams to set the default figure size to 10 inches by 8 inches:


plt.rcParams['figure.figsize'] = [10, 8]

How can I put the title at the bottom of a plot in matplot lib?

Search for: How can I put the title at the bottom of a plot in matplot lib?

API for title function

1. If this is negative the title is at the bottom.

2. Vertical Axes location for the title (1.0 is the top). If None (the default) and rcParams["axes.titley"] (default: None) is also None, y is determined automatically to avoid decorators on the Axes.

How can I rename columns in a pandas dataframe?

Search for: How can I rename columns in a pandas dataframe?

Pandas dataframe API refererence

Search for: Pandas dataframe API refererence

Pandas dataframe API

Pandas Userguide

Official Pandas cook book

How can I insert an extra column of data into a pandas dataframe?

Search for: How can I insert an extra column of data into a pandas dataframe?


df["new-column"]= new-series

#Take a column and multiply by 2
x = df[['Temperature']] * 2

#Rename the column to something new
#Do it in place
x.rename(columns={"Temperature":"Col3"},inplace=True)

#Copy an old data frame into a new data frame
ndf = df.copy()

#Insert a new column as is
#Notice that the right hand side op yields a Series object
ndf["Col3"] = x["Col3"]

#Insert yet another column by directly transorming
#an old column
ndf["Col4"] = x["Col3"] * 0.25

#print the new dataframe
ndf

    Day Tmp  Col3  Col4
**************************
0   1   50   100   25.0
1   2   51   102   25.5
2   3   52   104   26.0
3   4   48   96   24.0
4   5   47   94   23.5
5   6   49   98   24.5
6   7   46   92   23.0

plt.figure()

plt.xlabel()

plt.ylabel()

plt.title()

plt.plot()

plt.subplots()

plt.rcParams()

plt.legend()

#Control the overall "Figure" of the plot
plt.figure(figsize=[6,6])
plt.xlabel("Day")
plt.ylabel("Temp")
plt.title("Day vs Temp",{'color':'red','fontweight':'bold'}, 'right', y=-0.2)

#Draw multiple lines
TempLine = plt.plot(ndf["Day"],ndf["Temperature"],linewidth=4,label="TempLine")
col3Line = plt.plot(ndf["Day"],ndf["Col3"],linewidth=4,label="Col3 line")
col4Line = plt.plot(ndf["Day"],ndf["Col4"],linewidth=4, label="Col4 line")

#The label on each plt.plot() method is important
#For that to show up in legend
#loc=best, upper left, upper right etc
#See the API for legend for lot of options
plt.legend(loc="best", shadow=True, fontsize="large")

#enabled gridding
plt.grid()

Anatomy of matplot lib, quick intro, written with Jupyter book

The quick start guide has a cryptic but speaks of Figure, Axes, and axis

What is a reasonable good start: The pyplot shortcut docs at homepage

Understand rcParams here

You can better understand multiple drawings, axes, subplots here

A subplot and an axes appears synonymous


# First create some toy data:
x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)

# Create just a figure and only one subplot
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('Simple plot')

# Create two subplots and unpack the output array immediately
f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
ax1.plot(x, y)
ax1.set_title('Sharing Y axis')
ax2.scatter(x, y)

# Create four polar axes and access them through the returned array
fig, axs = plt.subplots(2, 2, subplot_kw=dict(projection="polar"))
axs[0, 0].plot(x, y)
axs[1, 1].scatter(x, y)

# Share a X axis with each column of subplots
plt.subplots(2, 2, sharex='col')

# Share a Y axis with each row of subplots
plt.subplots(2, 2, sharey='row')

# Share both X and Y axes with all subplots
plt.subplots(2, 2, sharex='all', sharey='all')

# Note that this is the same as
plt.subplots(2, 2, sharex=True, sharey=True)

# Create figure number 10 with a single subplot
# and clears it if it already exists.
fig, ax = plt.subplots(num=10, clear=True)

Can I use pyplot to draw to subplots?

Search for: Can I use pyplot to draw to subplots?

Drawing on multiple plots

Can you switch the current subplot using pyplot?

Search for: Can you switch the current subplot using pyplot?

Here is an SOF discussion on that

Show images for: Figure and axes matplotlib