Chevron linestyle in matplotlib - python

Is it possible to make a dashed linestyle using more complicated shapes in matplotlib (or any other python plotting library)? It's easy to make a linestyle with different spacings and combinations of dots and dashes, but I'm after something like this:
I can envision a way of doing it by writing a function from scratch to take a custom chevron marker style and working out the angle to display it at and the correct spacing etc. However that seems like an overly complicated way to address the problem that will easily break down for things like different specified line widths.

If you find a better latex symbol, you could do something like this.
import numpy as np
import matplotlib
matplotlib.rc('text', usetex=True)
matplotlib.rcParams['text.latex.preamble'] = [r'\boldmath', r'\usepackage{amsmath}', r'\usepackage{amssymb}', r'\usepackage{fontawesome}']
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot('111')
ax.plot(np.linspace(0,10,10),np.repeat(10,10),marker='$>$',ls='',ms=50,mew=10)
plt.show()
Look at the symbols in the fontawesome latex package, it might have something closer to what you're wanting. Then you can substitute the marker marker='$>$' for another latex symbol.

Related

Use scientific notation for Python plots by default

Simple question: how do I get Python to use scientific notation in its plots by default? From various posts on SO I can write something like
from numpy import linspace
import matplotlib.pyplot as plt
plt.figure()
plt.plot(linspace(1e6,2e6),linspace(1e6,1e7))
plt.figure()
plt.plot(linspace(8e6,9e6),linspace(2e6,2.5e7))
plt.ticklabel_format(style='sci', axis='both', scilimits=(-2,2))
plt.show()
but ticklabel_format only acts on the last plot generated by matplotlib. (If plt.ticklabel_format() is put at the beginning of the code, I also get a blank figure showing the x,y axes.)
You can modify the default behaviour of matplotlib by edditing your "rc" file. See Customizing matplotlib.
In you case, it looks like you could adjust the item:
axes.formatter.limits : -2, 2 # use scientific notation if log10
# of the axis range is smaller than the
# first or larger than the second

Using a colormap for matplotlib line plots

I’d like to employ the reverse Spectral colormap ,
https://matplotlib.org/examples/color/colormaps_reference.html
for a lineplot.
This works fine with a hex bin plot::
color_map = plt.cm.Spectral_r
image = plt.hexbin(x,y,cmap=color_map)
but when I do
ax1.plot(x,y, cmp=color_map)
this gives me::
AttributeError: Unknown property cmap
Note, I just want to set the colormap and let matplotliob do the rest; i.e. I don't want to have a color=' argument in the .plot command.
You can have a look at this solution - the third variant is what you want:
https://stackoverflow.com/a/57227821/5972778
You need to know how many lines you're plotting in advance, as otherwise it doesn't know how to choose the colours from the range.
I think that seaborn's color_palette function is very convenient for this purpose. It can be used in a with statement to temporarily set the color cycle for a plot or set of plots.
For example:
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
with sns.color_palette("Spectral", n_colors=10):
plt.plot(np.random.rand(5, 10))
You can use with any predefined matplotlib or seaborn colormap, or provide a custom sequence of colors.

Border on errorbars in matplotlib/python

I am looking for a way to set a black border on the errorbars in my plot,
The following code:
ax.errorbar(x, y, yerr, fmt='o', label='label',color="#8da0cb",capthick=2, elinewidth=2,zorder=10)
produces:
I find it more aesthetically pleasing if there was a black border around the errorbar like there is on the marker.
Thanks for any help you can provide
Not a great solution, but you could get close by plotting the errorbars again behind your original ones, with a wider line and cap thinkness, and setting the colour of those ones to black. We can make use of the zorder kwarg to put them behind the others.
Heres a MWE:
import matplotlib.pyplot as plt
import numpy as np
# Fake data
x=np.arange(0,5,1)
y=np.ones(x.shape)
yerr = np.ones(x.shape)/4.
# Create figure
fig,ax = plt.subplots(1)
# Set some limits
ax.set_xlim(-1,5)
ax.set_ylim(-2,4)
# Plot errorbars with the line color you want
ax.errorbar(x,y,yerr, fmt='o',color='r',capthick=2,elinewidth=2,capsize=3,zorder=10)
# Plot black errorbars behind (lower zorder) with a wider line and cap thinkness
ax.errorbar(x,y,yerr, fmt='o',color='k',capthick=4,elinewidth=4,capsize=4,zorder=5)
plt.show()
Again, not a perfect solution, but at least it allows you to include it in the legend. This time, rather than plot the errorbars twice, we will use the matplotlib.patheffects module to add a Stroke to the errorbars.
errorbar returns several Line2D and LineCollection objects, so we need to apply the stroke to each of the relevant ones.
import matplotlib.patheffects as path_effects
e = ax.errorbar(x,y,yerr, fmt='o',color='r',capthick=2,elinewidth=2, label='path effects')
e[1][0].set_path_effects([path_effects.Stroke(linewidth=4, foreground='black'),
path_effects.Normal()])
e[1][1].set_path_effects([path_effects.Stroke(linewidth=4, foreground='black'),
path_effects.Normal()])
e[2][0].set_path_effects([path_effects.Stroke(linewidth=4, foreground='black'),
path_effects.Normal()])
ax.legend(loc=0)
As far as I can see from the information provided in the webpage of pyplot I do not see a valid kwargs that exists for what you are asking.
There exists mfc, mec, ms and mew which are markerfacecolor, markeredgecolor, markersize and markeredgewith. It can probably be asked in GitHub so that people take this into consideration and add it in the next version of matplotlib.
Also taking a look at the answer for this question asked in Stackoverflow, I don't believe it can be done.

using more than one linestyle in the same trend line with matplotlib

I want to plot a line using the bold linestyle='k-' and after a certain value on the axes, I want the same line as dashed ('k--') or vice-versa. I want to show the dashed part as an extension to the bold line. One way to do this is to treat them as two individual plots and use different linestyles. I have attached the figure of an example. Just wondering if there was any other way to do this!
Yes it can be done. Following the suggestion given by #tom, one such example is:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(1,2,10)
y = np.linspace(1,2,10)
plt.plot(x[:4],y[:4],'-ko',x[3:],y[3:],'--ko')
plt.show()
This produces a plot:

Subscripting text in matplotlib labels

this is my first question and I am a noob at python. So probably more to follow...
I would like to create a figure with matplotlib. In the labels, I would like to include a chemical formula, which involves subscripts (I think the same would work for superscripts...).
Anyway, I have no idea, how the label would have to look like.
import numpy as nu
import pylab as plt
x = nu.array([1,2,3,4])
y = nu.array([1,2,3,4])
plt.plot(x,y, label='H2O')
plt.legend(loc=1)
plt.show()
Ok, this gives me a plot with the label "H2O". How can I subscript the "2" in the label, as is common for chemical formulae?
I searched the web, but I didn't find anything useful yet.
I figured that I could use
from matplotlib import rc
rc['text', usetex=True]
but I don't want to use it (I know how to use LaTeX, but I don't want here).
Another option is:
label='H$_2$O'
but this changes the font (math).
There MUST be a way, how does subscripting in matplotlib-legends work?
Thanks a lot!
Try to change this line
plt.plot(x,y, label='H2O')
for this:
plt.plot(x,y, label='$H_2O$')
It shows with the font math.
Or also you can use the unicode character for that: ₂ (0xE2 / ₂)
plt.plot(x,y, label=u'H₂O')
or instead:
plt.plot(x,y, label=u"H\u2082O")
Please, note that unicode strings are noted as u"" instead than "".

Categories