How can I increase the size of \bullet and \blacktriangledown in matplotlib plot for additional text in the legend? I have
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.pyplot import fig
... [functions]
plt.xlabel("X-label")
plt.xlabel("Y-label")
plt.legend(['8 $\\times (x+y^2)$'],
title=$\\bullet$ syst. A \n $\\bigblacktriangledown$ syst. B,
loc='center left', bbox_to_anchor=(1.02, 0.5))
plt.savefig("05042022.pdf", bbox_inches="tight")
and if I use \bigblacktriangledown I get the error Unknown symbol: \bigblacktriangledown, found u'\' (at char 0), (line:1, col:1) and if I use \large, I get:
Unknown symbol: \large, found u'\' (at char 1), (line:1, col:2).
Related
How can I set a default set of colors for plots made with matplotlib? I can set a particular color map like this
import numpy as np
import matplotlib.pyplot as plt
fig=plt.figure(i)
ax=plt.gca()
colormap = plt.get_cmap('jet')
ax.set_color_cycle([colormap(k) for k in np.linspace(0, 1, 10)])
but is there some way to set the same set of colors for all plots, including subplots?
Sure! Either specify axes.color_cycle in your .matplotlibrc file or set it at runtime using matplotlib.rcParams or matplotlib.rc.
As an example of the latter:
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
# Set the default color cycle
mpl.rcParams['axes.prop_cycle'] = mpl.cycler(color=["r", "k", "c"])
x = np.linspace(0, 20, 100)
fig, axes = plt.subplots(nrows=2)
for i in range(10):
axes[0].plot(x, i * (x - 10)**2)
for i in range(10):
axes[1].plot(x, i * np.cos(x))
plt.show()
Starting from matplotlib 1.5, mpl.rcParams['axes.color_cycle'] is deprecated. You should use axes.prop_cycle:
import matplotlib as mpl
mpl.rcParams['axes.prop_cycle'] = mpl.cycler(color=["r", "#e94cdc", "0.7"])
In the version of 2.1.0, the below works for me, using set_prop_cycle and module cycler
from cycler import cycler
custom_cycler = (cycler(color=['r','b','m','g']))
ax.set_prop_cycle(custom_cycler)
you can add additional line attribute
custom_cycler = (cycler(color=['r','b','m','g']) + cycler(lw=[1,1,1,2]))
'ax' comes from ax=plt.axes() or any axes generator
I'm trying to plot netcdf raster values of snowfall data in a text format overlaying what I currently have (mentioned further below). Example, something like this below:
Example
This is all the relevant code I have so far. I excluded the non relevant code. I tried plt.text and it gave me "ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()"
What I have plotted so far
import numpy
from datetime import datetime
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import cartopy.mpl.ticker as cticker
import matplotlib.pyplot as plt
from matplotlib import ticker, patheffects
from metpy.units import units
import numpy as np
import numpy.ma as ma
from scipy.ndimage import gaussian_filter, maximum_filter, minimum_filter
import xarray as xr
from metpy.plots import USCOUNTIES
from gradient import Gradient
import pandas as pd
import matplotlib.colors as col
#Open NOAA Snowfall dataset
ds = xr.open_dataset('sfav2_CONUS_2021093012_to_2022042512.nc')
ds
lat = ds.lat
lon = ds.lon
#converts snowfall data to inches
snowdata = ds['Data'] * 39
plt.text(lon, lat, snowdata, transform=datacrs)
As far as I know there isn't a vectorized way of plotting text (plt.text or plt.annotated). So you'll have to loop over the arrays and plot each point.
import matplotlib.pyplot as plt
import matplotlib.patheffects as PathEffects
import cartopy.crs as ccrs
import numpy as np
data = np.random.rand(18, 9)
lons, lats = np.mgrid[-17:18:2, 8:-9:-2]
lons = lons * 10
lats = lats * 10
fig, ax = plt.subplots(figsize=(10, 5), dpi=86, facecolor="w", subplot_kw=dict(projection=ccrs.EqualEarth()))
ax.pcolormesh(lons, lats, data, cmap="coolwarm", alpha=.2, transform=ccrs.PlateCarree())
ax.coastlines()
for val, lat, lon in zip(data.flat, lats.flat, lons.flat):
ax.text(
lon, lat, f"{val:1.1f}", ha="center", va="center", transform=ccrs.PlateCarree(),
path_effects=[PathEffects.withStroke(linewidth=3, foreground="w", alpha=.5)],
)
I have a data set of positive values and zero's that I would like to show on the log scale. To represent zero's I use 'symlog' option, but all zero values are mapped into one point on swarmplot. How to fix it?
import numpy as np
import seaborn as sns
import pandas as pd
import random
import matplotlib.pyplot as plt
n = 100
x = np.concatenate(([0]*n,np.linspace(0,1,n),[5]*n,np.linspace(10,100,n),np.linspace(100,1000,n)),axis=None)
data = pd.DataFrame({'value': x, 'category': random.choices([0,1,2,3], k=len(x))})
f, ax = plt.subplots(figsize=(10, 6))
ax.set_yscale("symlog",linthreshy=1.e-2)
ax.set_ylim(ymax=1000)
sns.swarmplot(x="category", y="value", data=data)
sns.despine(left=True)
link to the resulting plot
Ran into an interesting problem with the behavior of the text annotation functions in cartopy following the documentation which I don't think should be doing this - believe its related to how the text method takes the transform and applies it, perhaps similar to the issue shown here for .annotate (Why the annotate worked unexpected here in cartopy?). Basically no matter what is specified in terms of lat/lon and the transform it always plots at the center point of the plot. Code sample below:
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import cartopy.io.shapereader as shpreader
from matplotlib.colors import BoundaryNorm
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import matplotlib.patheffects as path_effects
def basic_map(proj):
fig = plt.figure(figsize=(12, 8))
view = fig.add_axes([0, 0, 1, 1], projection=proj)
view.set_extent([-120, -73, 23, 50])
view.add_feature(cfeature.STATES.with_scale('50m'))
view.add_feature(cfeature.OCEAN.with_scale('50m'),facecolor='white')
view.add_feature(cfeature.COASTLINE.with_scale('50m'))
view.add_feature(cfeature.BORDERS, linestyle=':')
return fig, view
proj = ccrs.AlbersEqualArea(central_longitude=-97.0000, central_latitude=38.0000)
fig, view = basic_map(prod)
view.text(-70,41, 'Northeast', color='black', fontsize=20, fontweight='bold',transform=proj,
path_effects=[path_effects.withSimplePatchShadow(),path_effects.PathPatchEffect(edgecolor='black', linewidth=0.6,facecolor='black')])
I am using numpy and matplotlib in Python3.
The following code is causing the error:
import matplotlib
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from matplotlib.axes import Subplot as plt
from matplotlib import pylab
a=[1,1]
b=[1,1]
fsam = 48000
w, h = freqz(b, a, worN=2000)
plt.plot(((fsam-8000) * 0.5 / np.pi) * w, abs(h), label=" ")
The actual error with matplotlib 1.3.x:
File "/usr/local/lib/python3.2/dist-packages/matplotlib-1.3.x-py3.2-linux-x86_64.egg/matplotlib/axes.py", line 4119, in plot
if not self._hold:
AttributeError: 'numpy.ndarray' object has no attribute '_hold'
The actual error with matplotlib 1.2.0:
Traceback (most recent call last):
File "/home/christoph/audio_measurement/AudioTools/AudioTools.py", line 222, in <module>
main()
File "/home/christoph/audio_measurement/AudioTools/AudioTools.py", line 216, in main
form = AppForm()
File "/home/christoph/audio_measurement/AudioTools/AudioTools.py", line 39, in __init__
self.on_draw()
File "/home/christoph/audio_measurement/AudioTools/AudioTools.py", line 80, in on_draw
self.transfer = Transfer(self.canvas)
File "/home/christoph/audio_measurement/AudioTools/Transfer.py", line 42, in __init__
plt.plot(((fsam-8000) * 0.5 / np.pi) * w, abs(h), label=" ")
File "/usr/local/lib/python3.2/dist-packages/matplotlib/axes.py", line 3995, in plot
if not self._hold: self.cla()
AttributeError: 'numpy.ndarray' object has no attribute '_hold'
Transfer is the class, which plots onto the canvas.
I had a look at the length of the coefficients a and b, but they did not effect the result.
I could not find anything on that. Does anyone know whats going wrong?
Normally I'd use import matplotlib.pyplot as plt with plt.plot, plt.subplot, plt.show, etc -- or even just from pylab import *. Anyway, this line
from matplotlib.axes import Subplot as plt
is the reason you have an unbound plot function that's trying to operate on the ndarray argument. Subplot needs to be instantiated. This should work:
import numpy as np
from scipy.signal import freqz
import matplotlib
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from matplotlib.axes import Subplot
fig = Figure()
ax = Subplot(fig, 111)
fig.add_subplot(ax)
canvas = FigureCanvas(fig)
a=[1,1]
b=[1,1]
fsam = 48000
w, h = freqz(b, a, worN=2000)
ax.plot(((fsam-8000) * 0.5 / np.pi) * w, abs(h), label=" ")
canvas.show()