[PYTHON] Various colorbars with Matplotlib

In the case of a two-dimensional plot, the types of data that can be expressed are up to three types using x-axis, y-axis and color. Following the MATLAB edition (https://qiita.com/Yuricst/items/1594cacb930bd4fa6d63), a memo about adding a colorbar in plot with Matplotlib in Python. (Even if it is not the optimal solution, it seems that this method will be enough for the time being. It will be updated from time to time.)

For scatter plots ( plt.scatter)

In the case of scatter, it is fairly simple, specify the array you want to use as a color parameter when using `scatter ()` with `c```, and specify the color map cmap``` Just specify with. Note that the `` fig.colorbar ()` `` used to add the colorbar requires a mappable object, so the scatter itself must be assigned as an object (im0 in the example below). .. When using subplot, if the color parameters are the same, there is no problem even if you do not assign all subplots as objects.

# assign color array
cc = transfer_df['Jacobi_LPO']

plt.rcParams["font.size"] = 16
fig, axs = plt.subplots(1, 3, figsize=(15, 6))
im0 = axs[0].scatter(transfer_df['loi_cost']*1000, transfer_df['incl'], c=cc, cmap='plasma', s=15, marker='x')
axs[0].set_xlabel('LOI cost [m/sec]')
axs[0].set_ylabel('Inclination [deg]')
axs[0].grid(True)

axs[1].scatter(transfer_df['loi_cost']*1000, transfer_df['raan'], c=cc, cmap='plasma', s=15, marker='x')
axs[1].set_xlabel('LOI cost [m/sec]')
axs[1].set_ylabel('RAAN [deg]')
axs[1].grid(True)

axs[2].scatter(transfer_df['loi_cost']*1000, -transfer_df['tof_EM_SOI']*Tstar_EM/(60*60*24), c=cc, cmap='plasma', s=15, marker='x')
axs[2].set_xlabel('LOI cost [m/sec]')
axs[2].set_ylabel('Tof til lunar SOI [days]')
axs[2].grid(True)


fig.colorbar(im0, label='LPO Jacobi')
plt.suptitle(f'Moon SOI leg, beta = {transfer_df.iloc[0,:]['beta0']}')
plt.tight_layout(rect=[0, 0.03, 1, 0.95])
plt.show()

For trajectories (`` `plt.plot```)

For plot, the process gets a little complicated. Roughly speaking --Save the data you want to plot in `points``` --Assign points``` and color bars in LineCollection --Added LineCollection to `` line``` It feels like (I wonder?).

# plot of the transfer (xy-plot)
fig, axs = plt.subplots(1, 1, figsize=(12,10))
plt.rcParams["font.size"] = 20

for j in tqdm( range(len(df_peritarg)) ):  
    # generate segments
    points = np.array([proptry["x_arr"] *Lstar , proptry["y_arr"] *Lstar]).T.reshape(-1, 1, 2)
    segments =np.concatenate([points[:-1], points[1:]], axis=1)
    
    loi_color = df_peritarg.iloc[j,:]["time2perilune"]*Tstar/86400 * np.ones(( len(proptry["x_arr"]) ,))
    
    # create color bar
    norm = plt.Normalize(min( df_peritarg["time2perilune"] )*Tstar/86400, max( df_peritarg["time2perilune"])*Tstar/86400)
    lc = LineCollection(segments, cmap='Reds', norm=norm)
    # Set the values used for colormapping
    lc.set_array( loi_color )
    lc.set_linewidth(0.8)
    line = axs.add_collection(lc)

# display colorbar
fig.colorbar(line, ax=axs, label="Transfer time [days]")

axs.grid()
axs.set_title(f'Targeting from {familydf.iloc[0,:]["family"]}')
axs.set_xlabel('x [km]')
axs.set_ylabel('y [km]')
axs.set_xlim(300000, 500000)
axs.set_ylim(-60000, 60000)
axs.set_aspect('equal')

Recommended Posts

Various colorbars with Matplotlib
Japanese with matplotlib
Animation with matplotlib
Histogram with matplotlib
Animate with matplotlib
2-axis plot with Matplotlib
Heatmap with Python + matplotlib
Band graph with matplotlib
Learn with Cheminformatics Matplotlib
Real-time drawing with matplotlib
3D plot with matplotlib
Adjust axes with matplotlib
Graph Excel data with matplotlib (1)
Try using matplotlib with PyCharm
Graph Excel data with matplotlib (2)
One-liner addition with various scripts
Stackable bar plot with matplotlib
Manipulate various databases with Python
Various memorandums developed with Choregraphe
Gradient color selection with matplotlib
Animate multiple graphs with matplotlib
Create plot animation with Python + Matplotlib
A python graphing manual with Matplotlib.
Inference & result display with Tensorflow + matplotlib
Japaneseize Matplotlib with Alpine using Docker
[Python] font family and font with matplotlib
Draw Japanese with matplotlib on Ubuntu
Draw a loose graph with matplotlib
Versatile data plotting with pandas + matplotlib
Various Fine Tuning with Mobilenet v2
Heatmap with Dendrogram in Python + matplotlib
Easy Japanese font setting with matplotlib
Easy to draw graphs with matplotlib
Continuously color with matplotlib scatter plot
Draw Lyapunov Fractal with Python, matplotlib
When matplotlib doesn't work with python2.7
Lognormal probability plot with Python, matplotlib
Easy animation with matplotlib (mp4, gif)
Write a stacked histogram with matplotlib
Implement "Data Visualization Design # 2" with matplotlib
Handle various date formats with pandas
How to title multiple figures with matplotlib
[Python] Set the graph range with matplotlib
GUI programming with kivy ~ Part 4 Various buttons ~
Adjust the spacing between figures with Matplotlib
Align the size of the colorbar with matplotlib
Try drawing a normal distribution with matplotlib
Make a partially zoomed figure with matplotlib
Write SVG graphs with matplotlib on heroku
Display Japanese graphs with VS Code + matplotlib
Heat Map for Grid Search with Matplotlib
Set the xticklabels color individually with matplotlib
Draw hierarchical axis labels with matplotlib + pandas
[Python] Let's make matplotlib compatible with Japanese
1. Statistics learned with Python 1-3. Calculation of various statistics (statistics)
Display markers above the border with matplotlib
Match the colorbar to the figure with matplotlib
[Jupyter Notebook memo] Display kanji with matplotlib
Various ways to destroy resources with scope
Write a nice pie chart with matplotlib
Make common settings with subplot of matplotlib