#131 Custom a Matplotlib scatterplot

Matplotlib allows to make scatter plots with python using the plot function. This page aims to provide a few elements of customization. For every example, we need a few libraries and to create a dataset:

# libraries
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

# dataset
df=pd.DataFrame({'x': range(1,101), 'y': np.random.randn(100)*80+range(1,101) })
Marker shape

Just use the marker argument of the plot function to custom the shape of the argument. The figure on the right gives you the main possibilities offered by python. (Code to make the figure provided as well)

# === Left figure:
plt.plot( 'x', 'y', data=df, linestyle='none', marker='*')
plt.show()

# === Right figure:
all_poss=['.','o','v','^','>','<','s','p','*','h','H','D','d','1','','']

# to see all possibilities:
# markers.MarkerStyle.markers.keys()

# set the limit of x and y axis:
plt.xlim(0.5,4.5)
plt.ylim(0.5,4.5)

# remove ticks and values of axis:
plt.xticks([])
plt.yticks([])
#plt.set_xlabel(size=0)

# Make a loop to add markers one by one
num=0
for x in range(1,5):
  for y in range(1,5):
    num += 1
    plt.plot(x,y,marker=all_poss[num-1], markerfacecolor='orange', markersize=23, markeredgecolor="black")
    plt.text(x+0.2, y, all_poss[num-1], horizontalalignment='left', size='medium', color='black', weight='semibold')
Marker size

To change marker size, juste use the markersize argument…

plt.plot( 'x', 'y', data=df, linestyle='none', marker='D', markersize=16)
plt.show()
Marker color

The color is controlled by the markerfacecolor and markeredgecolor arguments. There are several ways to call a color, see this dedicated page for more information.

plt.plot( 'x', 'y', data=df, linestyle='none', markerfacecolor='skyblue', marker="o", markeredgecolor="black", markersize=16)
plt.show()
Marker edge

You can control marker edge width and color:

plt.plot( 'x', 'y', data=df, linestyle='none', marker='D', markersize=16, markeredgecolor="orange", markeredgewidth=5)
plt.show()

Leave a Reply

Your email address will not be published.