Search code examples
pythonmatplotlib

How to change scientific notation form in Matplotlib


This is my code.

time = sig[:, 0]                                                    # data first column: time
displacement = sig[:, 1]                                            # data second column: displacement

font = {'family': 'Times New Roman', 'weight': 'bold', 'size': 16}  
fig, ax = plt.subplots(figsize = (9, 8))                            # set figure size (width,height)

ax.plot(time, displacement, linewidth = 2)                          

ax.set_xlim(0, 3e-3)                                                # set x-axis limit
ax.set_ylim(-4e-6, 1e-6)                                            # set y-axis limit

ax.set_xticklabels([0, 0.5, 1, 1.5, 2, 2.5, 3])
ax.tick_params(labelsize = 16)                                      # tick_params can only change label size                     
labels = ax.get_xticklabels() + ax.get_yticklabels()                
for label in labels:                                                # thus use for loop(?) change font name and weight 
    label.set_fontname('Times New Roman')
    label.set_fontweight('bold')

ax.set_xlabel('Time (msec.)', font)
ax.set_ylabel('Displacement (m)', font)

plt.show() 

And this is the code's result.

But actually, that's what I want to get.

How can I change the notation form from 1e-6 to 10^-6 and also make the font bold.


Solution

  • To change the scientific notation of ticklabel:

    ax.ticklabel_format(useMathText=True)
    

    To change the text properties, grab the text object with:

    ty = ax.yaxis.get_offset_text()
    
    ty.set_fontweight('bold')
    ty.set_size(16)