matplotlib boxplot color - numpy

I'm trying to create a box & whisker plot of a set of data binning y versus x. I found an useful example in making binned boxplot in matplotlib with numpy and scipy in Python. The question is now very simple. How can I specify the color of the boxes in matplotlib.pyplot.boxplot as I would like to set it transparent in order to let the reader also to see the original data. I know there exists the example shown in http://matplotlib.sourceforge.net/examples/pylab_examples/boxplot_demo2.html but is anything simpler than this? It looks strange the impossibility to set the color of the boxes directly in boxplot
Thank you in advance

You could just render the original data as a scatter plot behind the boxplot and then hide the fliers of the boxplot.
import pylab
import numpy
pylab.figure()
data = [numpy.random.normal(i, size=50) for i in xrange(5)]
for x, y in enumerate(data):
pylab.scatter([x + 1 for i in xrange(50)], y, alpha=0.5, edgecolors='r', marker='+')
bp = pylab.boxplot(data)
pylab.setp(bp['boxes'], color='black')
pylab.setp(bp['whiskers'], color='black')
pylab.setp(bp['fliers'], marker='None')
pylab.xlim(0,6)
pylab.show()

Related

How to avoid matplotlib to simplify my Y axis in figure?

the image of what I mean in my question
I'm using BMP280 to measure Temperature and Pressure using Raspberry.
I'm using matplotlib to make a graph, but the matplotlib simplify my Y axis bi adding +9.967e2.
is there any way to avoid matplotlib simplify my Y axis. Sorry I'm new to this so I don't know much.
I tried to search in google but I don't find anything. Maybe I'm using the wrong keyword as I don't know what should I search.
You can turn off the offset as shown in the examples here. For example, if you've made you plot with:
from matplotlib import pyplot as plt
plt.plot(x, y)
then you can turn off the offset with
ax = plt.gca() # get the axes object
# turn off the offset (on the y-axis only)
ax.ticklabel_format(axis="y", useOffset=False)
plt.show()
See the ticklabel_format docs for more info.

add text on plt.imshow

I have two ndarrays: Mat, labels
Currently I display Mat:
plt.imshow(Mat, cmap='gray', vmin=0, vmax=1, interpolation='None')
labels has the same shape as Mat, and lables[(i,j)] contains a label of Mat[(i,j)].
How can I show the label on each pixel?
The easiest approach uses Seaborn's heatmap. When annot=True it prints the data values into the cells. But annot= can also be a matrix of labels. In that case it is important to set the print format to string (fmt='s'). annot_kws= can set additional keywords, such as fontsize or color. x and yticklabels can be incorporated in the call to heatmap(), or be set afterwards using matplotlib.
An important benefit of the default coloring is that Sorn uses black on the light colored cells and white on the dark cells.
Here is an example that uses some utf8 characters as labels.
from matplotlib import pyplot as plt
import numpy as np
import seaborn as sns
M, N = 5, 10
mat = np.random.rand(M, N)
labels = np.random.choice(['X', '☀', '★', '♛'], size=(M, N))
ax = sns.heatmap(mat, cmap="inferno", annot=labels, annot_kws={'fontsize': 16}, fmt='s')
plt.show()
PS: There is a matplotlib example in the documentation to create something similar without Seaborn. It can be easily adapted to print strings from a different matrix, and also a test can be added to change the color depending on the cell darkness.

histogram2d heatmap manipulation

I created a heatmap from a scatterplot of csv values using the code i found from a different stackoverflow thread here Generate a heatmap in MatPlotLib using a scatter data set
This works but I'd like to edit the colours/smooth between bins etc. I've read this https://matplotlib.org/examples/color/colormaps_reference.html ...but my level of n00b is preventing swift progress. Does my current code seem ameanable to easy manipulation for interpolation between bins (smoothing) or at least a colour change, or do I need to create my heatmap in a different way to gain more control? (the heatmap will represent how often a space is used in time, based on x y values of a tracked item)
Thanks , any help much appreciated.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import csv
with open('myfile.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
y = []
x = []
for row in readCSV:
x.append(float(row [0]))
y.append(float(row [1]))
print (x, y)
heatmap, xedges, yedges = np.histogram2d(x,y,bins=20)
extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]
plt.clf()
plt.imshow(heatmap.T, extent=extent)
plt.show()

matplotlib surface plot with hidden zaxis

when I change the viewpoint of plot_surface in matplolib in (90,0), the zaxis is not clear, and it's useless in this plot. I want to generate the image same as matlab as below
matlab surf with view (0,90),with contour lines
I used matplotlib function imshow can generate matrix image, but there are no lines (similar in contourplot lines)in the image. how can i generate the image with plot_surface in python with a viewpoint of (90,0),bu without zaxis?
matplotlib with plot_surface,view(90,0),withou lines and zaxis
You can use contourf from matplotlib:
import matplotlib.pyplot as plt
import numpy as np
X, Y = np.meshgrid(range(100), range(100))
Z = X**2+Y**2
plt.contourf(X, Y, Z, [i for i in np.linspace(Z.min(),Z.max(),30)])
plt.show()
, which results in:

Change colour of curve according to its y-value in matplotlib [duplicate]

This question already has answers here:
Having line color vary with data index for line graph in matplotlib?
(4 answers)
Set line colors according to colormap
(1 answer)
Closed 8 years ago.
I'm trying to replicate the style of the attached figure using matplotlib's facilities.
Basically, I want to change the colour of the curve according to its y-value using matplotlib.
The plot you've shown doesn't have the color set by the vertical axis of the plot (which is what I would consider the y-value). Instead, it just has 8 different plots overlain, each with a different color, without stating what the color means.
Here's an example of something that looks like your plot:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
# some fake data:
x = np.linspace(0, 2*np.pi, 1000)
fs = np.arange(1, 5.)
ys = np.sin(x*fs[:, None])
for y, f in zip(ys, fs):
plt.plot(x, y, lw=3, c=cm.hot(f/5))
If you actually want the color of one line to change with respect to its value, you have to kind of hack it, because any given Line2D object can only have one color, as far as I know. One way to do this is to make a scatter plot, where each dot can have any color.
x = np.linspace(0, 2*np.pi, 1000)
y = np.sin(2*x)
plt.scatter(x,y, c=cm.hot(np.abs(y)), edgecolor='none')
Notes:
The color vector should range between 0 and 1, so if y.max() > 1, then normalize by it: c=cm.hot(y/y.max()) and make sure it's all positive.
I used edgecolor='none' because by default the scatter markers have a black outline which makes the it look less like a uniform line.
If your data is spaced too far, you'll have to interpolate the data if you don't want gaps between markers.