Determining matplotlib stylesheet keys - matplotlib

Is there a standard method for determining valid stylesheet keys for matplotlib? Currently I use a mixture of searching on SO, guesswork and this example stylesheet as a reference. Is there a complete list of valid keys for a stylesheets?
For example if I want to set the colour on a scatter graph to black I could use:
import matplotlib as plt
fig, ax = plt.subplots()
ax.scatter(x, y, color='k')
However axes.scatter.color is not a valid key for a stylesheet. I can set the marker type using the key scatter.marker, but scatter.marker.color doesn't exist.

All valid rc Params are part of the matplotlib rc file shown on the matplotlib page. (If you find a valid rc param that is missing in that file, please report it to the matplotlib GitHub tracker.)
You may also print a list of all rc Params as
import matplotlib.pyplot as plt
for k,v in plt.rcParams.items():
print(k)

Related

How to change bars' outline width in a displot?

I managed to make a displot as I intended with seaborn and the only thing I want to change is the bars' outline width. Specifically, I want to make it thinner. Here's the code and a sample of how the dataframe is composed.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
data_final = pd.merge(data, data_filt)
q = sns.displot(data=data_final[data_final['cond_state'] == True], y='Brand', hue='Style', multiple='stack')
plt.title('Sample of brands and their offering of ramen styles')
I'm specifying that the plot should only use rows where the cond_state is True. Here is a sample of the data_final dataframe.
Here is how the plot currently looks like.
I've tried various ways published online, but most of them use the deprecated distplot instead of displot. There also doesn't seem to be a parameter for changing the bars' outline width in the seaborn documentation for displot and FacetGrid
The documentation for the seaborn displot function doesn't have this parameter listed, but you can pass matplotlib axes arguments, such as linewidth = 0.25, to the seaborn.displot function to solve your problem.

Use a different matplotlibrc for savefig

I am using Jupyter Notebook, with a matplotlibrc style that's consistent with its theme set using jupyterthemes. That plotting style however does not look good if I want to export it to PNG to use it within my other documents.
How do I specify a different matplotlibrc when I do a savefig?
Most matplotlib style settings are applied at the moment the object they apply to is created.
You would hence need to create two different plots, one with the usual style of your notebook and another one with the style from the style file. The latter one would be the one to save.
A decent solution would be to create a plot in a function. You can then call this function within a context, with plt.style.context(<your style>): to give the figure a different style.
import matplotlib.pyplot as plt
def plot():
fig, ax = plt.subplots()
ax.plot([2,3,4], label="label")
ax.legend()
# Plot with general style of the notebook
plot()
# Plot with your chosen style for saved figures
with plt.style.context('ggplot'):
plot()
plt.savefig("dark.png")
#plt.close(plt.gcf()) # if you don't want to show this figure on screen
plt.show()
Relevant here: The matplotlib customizing guide.
Perusing matplotlib/__init__.py reveals a number of functions used for managing rcParams. To update rcParams from a file, use matplotlib.rc_file:
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.rc_file('/tmp/matplotlibrc')
plt.plot([0,1], [0,10])
plt.savefig('/tmp/out.png')
with /tmp/matplotlibrc containing
lines.linewidth : 10 # line width in points
lines.linestyle : -- # dashed line
yields
PS. In hindsight, having found rc_file, googling shows it is documented here.

Usetex in Matplotlib

When I try to obtain plots in which the axis (both formulae and text) are written in LaTeX standard roman font, I keep not obtaining the plot, but the code runs without warnings. In particular, this simple scatter with TeX code in the axis labels, in which I have put my better understanding of the documentation:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
x = np.linspace(0,1,100)
y = np.random.rand(100,1)
plt.rc('text', usetex=True)
plt.rc('font', family='roman')
plt.scatter(x, y, c='b', s=10)
plt.xlabel(r'$\lambda$ ($\AA$)',size='12')
plt.ylabel(r'$F_\alpha (W/m^2)$ ',size='12')
plt.title(r'A title in \LaTeX typography')
plt.show()
keeps yielding a message like <matplotlib.figure.Figure at 0x1f75d4750>, which I have met before, but I keep failing when trying to remedy this one. In addition, saving the plot (png or pdf) would not solve the issue, and if the problem is related to TeX, I have definitely not found any resource that can help. I use MacOS Sierra.

Annotating a box outside the box, matplotlib

I want the text to appear beside the box instead of inside it:
Here is what I did:
import matplotlib as mpl
import matplotlib.pyplot as plt
from custombox import MyStyle
fig = plt.figure(figsize=(10,10))
legend_ax = plt.subplot(111)
legend_ax.annotate("Text",xy=(0.5,0.5),xycoords='data',xytext=(0.5, 0.5),textcoords= ('data'),ha="center",rotation = 180,bbox=dict(boxstyle="angled, pad=0.5", fc='white', lw=4, ec='Black'))
legend_ax.text(0.6,0.5,"Text", ha="center",size=15)
Here is what it gives me:
Note: custombox is similar to the file that is written in this link:
http://matplotlib.org/1.3.1/users/annotations_guide.html
My ultimate aim is to make it look legend like where the symbol (angled box) appears beside the text that represents it.
EDIT 1: As suggested by Ajean I have annotated text separately but I can't turn of the text within the arrow
One way to do it would be to separate the text and the bbox (which you can reproduce using an arrow). The following gives me something close to what you want, I think.
import matplotlib.pyplot as plt
from matplotlib import patches
fig = plt.figure(figsize=(5,5))
ax = fig.add_subplot(111)
ax.annotate("Text", (0.4,0.5))
bb = patches.FancyArrow(0.5,0.5,0.1,0.0,length_includes_head=True, width=0.05,
head_length=0.03, head_width=0.05, fc='white', ec='black',
lw=4)
ax.add_artist(bb)
plt.show()
You can futz with the exact placement as needed. I'm not an expert on all the kwargs, so this may not be the best solution, but it will work.

Plotting points in 3d from text file using Matplotlib or Octave

Hi I have a text file containing three columns of numbers; one column each for the x,y,z coordinates of a bunch of points. All numbers are between 0 ad 1.
I want to plot all these points in the unit cube [0,1]x[0,1]x[0,1].
Please let me know how I can do this in Octave or MatPlot lib, whichever prduces a better quality image.
If I understand your question correctly, this is how it looks in Matplotlib:
This is the code to produce this plot:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
np.random.seed(101)
x,y,z = np.random.rand(3,20)
fig = plt.figure()
# version 1.0.x syntax:
#ax = fig.add_subplot(111, projection='3d')
# version 0.99.x syntax: (accepted by 1.0.x as well)
ax = Axes3D(fig)
ax.scatter(x,y,z)
fig.savefig('scatter3d.png')
As the code suggests, there are slight differences in how matplotlib version 0.99.1.1 and version 1.0.1 behave, as noted in this SO question/answer. I am using 0.99.1.1, and I had trouble using all the options available to 2D scatter plots, which should be the same for 3D plots as well. The full list of scatter features are listed here.
The above code resulted from looking at the matplotlib tutorial on 3D plotting.