How do I get these plots to use scientific notation for the colorbar units? [code]
- User
How do I get these plots to use scientific notation for the colorbar units?
plotted_artists['DQ2PHYS'] = nn_diff_DQ2PHYS.plot(ax=axs[1,0], add_colorbar=False, cmap='RdBu_r', vmin=var_settings['DQ2PHYS']['vmin'], vmax=var_settings['DQ2PHYS']['vmax']) axs[1,0].set_title(f'{labels[2]} dQl/dt Bias ({var_settings["DQ2PHYS"]["unit"]})') axs[1,0].invert_yaxis() axs[1,0].set_xlabel('Latitude') plotted_artists['DQ3PHYS'] = nn_diff_DQ3PHYS.plot(ax=axs[1,1], add_colorbar=False, cmap='RdBu_r', vmin=var_settings['DQ3PHYS']['vmin'], vmax=var_settings['DQ3PHYS']['vmax']) axs[1,1].set_title(f'{labels[3]} dQi/dt Bias ({var_settings["DQ3PHYS"]["unit"]})') axs[1,1].invert_yaxis() axs[1,1].set_xlabel('Latitude') Assistant
To display scientific notation on the colorbar for plots made with xarray's
.plot(), you can manually create and customize the colorbar usingmatplotlibafter plotting. Here's how you can do it:✅ Solution: Use
matplotlib.tickerto format the colorbarYou'll need to:
- Plot without a colorbar (
add_colorbar=False) - Create a colorbar manually
- Apply scientific notation formatting
Here’s how to modify your code:
import matplotlib.pyplot as plt import matplotlib.ticker as ticker # For DQ2PHYS plotted_artists['DQ2PHYS'] = nn_diff_DQ2PHYS.plot( ax=axs[1,0], add_colorbar=False, cmap='RdBu_r', vmin=var_settings['DQ2PHYS']['vmin'], vmax=var_settings['DQ2PHYS']['vmax'] ) axs[1,0].set_title(f'{labels[2]} dQl/dt Bias ({var_settings["DQ2PHYS"]["unit"]})') axs[1,0].invert_yaxis() axs[1,0].set_xlabel('Latitude') # Add colorbar with scientific notation cbar2 = plt.colorbar(plotted_artists['DQ2PHYS'], ax=axs[1,0]) cbar2.formatter = ticker.ScalarFormatter(useMathText=True) cbar2.formatter.set_powerlimits((0, 0)) # Forces scientific notation cbar2.update_ticks() # For DQ3PHYS plotted_artists['DQ3PHYS'] = nn_diff_DQ3PHYS.plot( ax=axs[1,1], add_colorbar=False, cmap='RdBu_r', vmin=var_settings['DQ3PHYS']['vmin'], vmax=var_settings['DQ3PHYS']['vmax'] ) axs[1,1].set_title(f'{labels[3]} dQi/dt Bias ({var_settings["DQ3PHYS"]["unit"]})') axs[1,1].invert_yaxis() axs[1,1].set_xlabel('Latitude') # Add colorbar with scientific notation cbar3 = plt.colorbar(plotted_artists['DQ3PHYS'], ax=axs[1,1]) cbar3.formatter = ticker.ScalarFormatter(useMathText=True) cbar3.formatter.set_powerlimits((0, 0)) cbar3.update_ticks()
🔍 Explanation:
ticker.ScalarFormatter(useMathText=True)uses LaTeX-style scientific notation (e.g.,1e4becomes ).set_powerlimits((0, 0))tells matplotlib to use scientific notation for all exponents.plt.colorbar(...)creates the colorbar for the given artist.
Let me know if you'd like to apply this globally or to subplots more programmatically!
- Plot without a colorbar (
- User
nn_diff_DQ2PHYS is an xarray object. Does that change your answer?
Assistant
No, the fact that
nn_diff_DQ2PHYSis an xarray DataArray doesn't change the approach — in fact, it fits perfectly with what we're doing.✅ Your situation:
You're using
.plot()from xarray, which returns a matplotlib QuadContourSet or imshow-like object, depending on the plot type. This object is needed to create a colorbar viaplt.colorbar(), and everything I provided before works seamlessly with xarray plotting.
🧠 Why It Still Works
When you do:
plotted_artists['DQ2PHYS'] = nn_diff_DQ2PHYS.plot(...)xarray internally uses matplotlib to generate the plot, and the return value (
plotted_artists['DQ2PHYS']) is a valid mappable object (like aQuadContourSetorMeshQuadGrid) that can be passed toplt.colorbar().So this line still works fine:
cbar2 = plt.colorbar(plotted_artists['DQ2PHYS'], ax=axs[1,0])And formatting with
ticker.ScalarFormatteralso applies just as well.
✔️ Final Code (unchanged, but confirmed safe for xarray)
Here's the full version again, now confirmed correct for use with xarray DataArrays:
import matplotlib.pyplot as plt import matplotlib.ticker as ticker # Plot DQ2PHYS plotted_artists['DQ2PHYS'] = nn_diff_DQ2PHYS.plot( ax=axs[1, 0], add_colorbar=False, cmap='RdBu_r', vmin=var_settings['DQ2PHYS']['vmin'], vmax=var_settings['DQ2PHYS']['vmax'] ) axs[1, 0].set_title(f'{labels[2]} dQl/dt Bias ({var_settings["DQ2PHYS"]["unit"]})') axs[1, 0].invert_yaxis() axs[1, 0].set_xlabel('Latitude') # Add scientific notation colorbar cbar2 = plt.colorbar(plotted_artists['DQ2PHYS'], ax=axs[1, 0]) cbar2.formatter = ticker.ScalarFormatter(useMathText=True) cbar2.formatter.set_powerlimits((0, 0)) cbar2.update_ticks() # Plot DQ3PHYS plotted_artists['DQ3PHYS'] = nn_diff_DQ3PHYS.plot( ax=axs[1, 1], add_colorbar=False, cmap='RdBu_r', vmin=var_settings['DQ3PHYS']['vmin'], vmax=var_settings['DQ3PHYS']['vmax'] ) axs[1, 1].set_title(f'{labels[3]} dQi/dt Bias ({var_settings["DQ3PHYS"]["unit"]})') axs[1, 1].invert_yaxis() axs[1, 1].set_xlabel('Latitude') # Add scientific notation colorbar cbar3 = plt.colorbar(plotted_artists['DQ3PHYS'], ax=axs[1, 1]) cbar3.formatter = ticker.ScalarFormatter(useMathText=True) cbar3.formatter.set_powerlimits((0, 0)) cbar3.update_ticks()
📌 Tip: Reusable Function (Optional)
If you’re making many such plots, consider wrapping the colorbar logic into a helper function:
def add_sci_colorbar(artist, ax, label=None): cbar = plt.colorbar(artist, ax=ax) cbar.formatter = ticker.ScalarFormatter(useMathText=True) cbar.formatter.set_powerlimits((0, 0)) cbar.update_ticks() if label: cbar.set_label(label) return cbarThen call:
add_sci_colorbar(plotted_artists['DQ2PHYS'], axs[1,0])Let me know if you'd like to apply this across all subplots programmatically!
- User
I tried accessing the colorbar of the xarray object and I got this error.
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In[54], line 1 ----> 1 plot_zonal_mean_tendency_bias('v6', 'squeezeformer', 'seed_7', actual_target) Cell In[53], line 57 55 axs[1,0].set_xlabel('Latitude') 56 cbar = plotted_artists['DQ2PHYS'].colorbar ---> 57 cbar.ax.yaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: f"{x:.1e}")) 59 plotted_artists['DQ3PHYS'] = nn_diff_DQ3PHYS.plot(ax=axs[1,1], add_colorbar=False, cmap='RdBu_r', vmin=var_settings['DQ3PHYS']['vmin'], vmax=var_settings['DQ3PHYS']['vmax']) 60 axs[1,1].set_title(f'{labels[3]} dQi/dt Bias ({var_settings["DQ3PHYS"]["unit"]})') AttributeError: 'NoneType' object has no attribute 'ax' Assistant
Thanks for sharing the error — it gives us a clear picture of what's going wrong.
❌ Problem Summary:
You're trying to access the colorbar via:
cbar = plotted_artists['DQ2PHYS'].colorbarBut this fails because
.colorbarisNone, which causes:AttributeError: 'NoneType' object has no attribute 'ax'This happens because xarray does not automatically create a colorbar object unless you explicitly ask for one using
add_colorbar=True. And even then, accessing it via.colorbarisn't reliable or documented behavior.
✅ Correct Way to Access and Format the Colorbar
As we discussed earlier, you need to create the colorbar manually with
plt.colorbar(), and then format its ticks.Here’s how to fix your code:
✅ Working Code (with Scientific Notation Formatter)
import matplotlib.pyplot as plt import matplotlib.ticker as ticker # Plot DQ2PHYS plotted_artists['DQ2PHYS'] = nn_diff_DQ2PHYS.plot( ax=axs[1, 0], add_colorbar=False, cmap='RdBu_r', vmin=var_settings['DQ2PHYS']['vmin'], vmax=var_settings['DQ2PHYS']['vmax'] ) axs[1, 0].set_title(f'{labels[2]} dQl/dt Bias ({var_settings["DQ2PHYS"]["unit"]})') axs[1, 0].invert_yaxis() axs[1, 0].set_xlabel('Latitude') # Add and format colorbar cbar = plt.colorbar(plotted_artists['DQ2PHYS'], ax=axs[1, 0]) cbar.ax.yaxis.set_major_formatter(ticker.ScalarFormatter(useMathText=True)) cbar.ax.yaxis.get_major_formatter().set_powerlimits((0, 0)) # Optional: rotate the colorbar tick labels for readability cbar.ax.tick_params(rotation=45)
🧠 Why Your Old Code Didn't Work:
plotted_artists['DQ2PHYS'].colorbardoesn’t exist becauseadd_colorbar=False.- Even if it did,
.colorbaris not a standard or documented property. - Always use
plt.colorbar(your_artist, ax=your_axis)to get and customize a colorbar.
✅ Bonus: Use Custom Formatter (if needed)
If you want more control (e.g., custom number of decimal places), here's an example using
FuncFormatter:def sci_notation(x, pos): return f"{x:.1e}" cbar.ax.yaxis.set_major_formatter(ticker.FuncFormatter(sci_notation))
Let me know if you'd like to apply this formatting globally to all subplots or make it reusable in a function!
- User
The colorbar in the original code gets added here:
var_order = ['DTPHYS', 'DQ1PHYS', 'DQ2PHYS', 'DQ3PHYS', 'DUPHYS', 'DVPHYS'] for ax, var_key in zip(axs.flat, var_order): img = plotted_artists[var_key] # Use the stored artist if img is not None: # Check if artist exists cbar = fig.colorbar(img, ax=ax, orientation='vertical', fraction=0.046, pad=0.04) else: print(f"Warning: No artist found for variable {var_key} to create colorbar.") Assistant
Thanks for showing the full colorbar creation loop — this helps a lot!
You're currently adding colorbars inside a loop using
fig.colorbar(...), and you want to format those colorbars to use scientific notation.
✅ Goal:
Format all colorbars in your loop to use scientific notation, like:
1e3→0.0001→
✅ Solution: Add Formatter Inside Loop
Here's your updated code with scientific notation formatting applied to each colorbar:
import matplotlib.ticker as ticker var_order = ['DTPHYS', 'DQ1PHYS', 'DQ2PHYS', 'DQ3PHYS', 'DUPHYS', 'DVPHYS'] for ax, var_key in zip(axs.flat, var_order): img = plotted_artists[var_key] # Use the stored artist if img is not None: # Check if artist exists cbar = fig.colorbar(img, ax=ax, orientation='vertical', fraction=0.046, pad=0.04) # Format the colorbar ticks with scientific notation cbar.ax.yaxis.set_major_formatter( ticker.ScalarFormatter(useMathText=True) ) cbar.ax.yaxis.get_major_formatter().set_powerlimits((0, 0)) cbar.update_ticks() else: print(f"Warning: No artist found for variable {var_key} to create colorbar.")
🧠 Explanation:
ticker.ScalarFormatter(useMathText=True)enables LaTeX-style scientific notation..set_powerlimits((0, 0))ensures that everything gets formatted in scientific notation (not just small or large values).cbar.update_ticks()forces the colorbar to redraw with the new format.
📌 Optional: Rotate Labels for Readability
If the numbers look cramped on the colorbar, you can rotate them:
cbar.ax.tick_params(rotation=45)Or even reduce the number of ticks:
cbar.locator = ticker.MaxNLocator(nbins=5) # Limit to 5 ticks cbar.update_ticks()
✅ Final Tip: Reusable Helper Function
If you're doing this often, wrap it up:
def format_colorbar(cbar): cbar.ax.yaxis.set_major_formatter( ticker.ScalarFormatter(useMathText=True) ) cbar.ax.yaxis.get_major_formatter().set_powerlimits((0, 0)) cbar.update_ticks()Then call it like:
cbar = fig.colorbar(img, ax=ax, ...) format_colorbar(cbar)
Let me know if you'd also like to adjust label formatting, font size, or units!
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.