Posts

Showing posts with the label Matplotlib

Apply MatplotLib Or Custom Colormap To OpenCV Image

Image
Answer : For Python >= 2.7, cmapy packages this functionality in a convenient way. Install it with: Python 2.7: pip install cmapy Python 3.x: pip3 install cmapy Or, for Anaconda (from conda-forge): conda install -c conda-forge cmapy And use it like this: import cv2 import matplotlib.pyplot as plt import cmapy # Read image. img = cv2.imread('imgs/woman.png') # Colorize. img_colorized = cv2.applyColorMap(img, cmapy.cmap('viridis')) # Display plt.imshow(img_colorized) plt.show() Different colormaps give something like this: See all the available colormaps in action here. Disclaimer: I wrote cmapy (because I needed this functionality for another project), and internally, it does pretty much the same as the other answers. In recent versions of OpenCV (starting with 3.3), there's an overload of applyColorMap , which allows you to provide a custom colormap (either 1 or 3 channel). I've modified verified.human's code to sim...

Change Xticklabels Fontsize Of Seaborn Heatmap

Image
Answer : Consider calling sns.set(font_scale=1.4) before plotting your data. This will scale all fonts in your legend and on the axes. My plot went from this, To this, Of course, adjust the scaling to whatever you feel is a good setting. Code: sns.set(font_scale=1.4) cmap = sns.diverging_palette(h_neg=210, h_pos=350, s=90, l=30, as_cmap=True) sns.clustermap(data=corr, annot=True, fmt='d', cmap="Blues", annot_kws={"size": 16}) Or just use the set_xticklabels: g = sns.clustermap(data=corr_s, annot=True, fmt='d',cmap = "Blues") g.ax_heatmap.set_xticklabels(g.ax_heatmap.get_xmajorticklabels(), fontsize = 16) To get different colors for the ticklabels: import matplotlib.cm as cm colors = cm.rainbow(np.linspace(0, 1, corr_s.shape[0])) for i, ticklabel in enumerate(g.ax_heatmap.xaxis.get_majorticklabels()): ticklabel.set_color(colors[i])

Changing Color And Marker Of Each Point Using Seaborn Jointplot

Image
Answer : Solving this problem is almost no different than that from matplotlib (plotting a scatter plot with different markers and colors), except I wanted to keep the marginal distributions: import seaborn as sns from itertools import product sns.set(style="darkgrid") tips = sns.load_dataset("tips") color = sns.color_palette()[5] g = sns.jointplot("total_bill", "tip", data=tips, kind="reg", stat_func=None, xlim=(0, 60), ylim=(0, 12), color='k', size=7) #Clear the axes containing the scatter plot g.ax_joint.cla() #Generate some colors and markers colors = np.random.random((len(tips),3)) markers = ['x','o','v','^','<']*100 #Plot each individual point separately for i,row in enumerate(tips.values): g.ax_joint.plot(row[0], row[1], color=colors[i], marker=markers[i]) g.set_axis_labels('total bill', 'tip', fontsize=16) Which gives me this: ...

Automatically Position Text Box In Matplotlib

Image
Answer : Just use annotate and specify axis coordinates. For example, "upper left" would be: plt.annotate('Something', xy=(0.05, 0.95), xycoords='axes fraction') You could also get fancier and specify a constant offset in points: plt.annotate('Something', xy=(0, 1), xytext=(12, -12), va='top' xycoords='axes fraction', textcoords='offset points') For more explanation see the examples here and the more detailed examples here. I'm not sure if this was available when I originally posted the question but using the loc parameter can now actually be used. Below is an example: import numpy as np import matplotlib.pyplot as plt from matplotlib.offsetbox import AnchoredText # make some data x = np.arange(10) y = x # set up figure and axes f, ax = plt.subplots(1,1) # loc works the same as it does with figures (though best doesn't work) # pad=5 will increase the size of padding between the border and t...

100x100 Image With Random Pixel Colour

Image
Answer : This is simple with numpy and pylab . You can set the colormap to be whatever you like, here I use spectral. from pylab import imshow, show, get_cmap from numpy import random Z = random.random((50,50)) # Test data imshow(Z, cmap=get_cmap("Spectral"), interpolation='nearest') show() Your target image looks to have a grayscale colormap with a higher pixel density than 100x100: import pylab as plt import numpy as np Z = np.random.random((500,500)) # Test data plt.imshow(Z, cmap='gray', interpolation='nearest') plt.show() If you want to create an image file (and display it elsewhere, with or without Matplotlib), you could use NumPy and Pillow as follows: import numpy, from PIL import Image imarray = numpy.random.rand(100,100,3) * 255 im = Image.fromarray(imarray.astype('uint8')).convert('RGBA') im.save('result_image.png') The idea here is to create a numeric array, convert it to a RGB image, and sa...

Assign Specific Colours To Data In Matplotlib Pie Chart

Image
Answer : Here's an idea you could try. Make a dictionary from your labels and colors, so each color is mapped to a label. Then, after making the pie chart, go in an assign the facecolor of the wedge using this dictionary. Here's an untested bit of code which might do what you are looking for: import numpy as np import matplotlib.pyplot as plt def mypie(slices,labels,colors): colordict={} for l,c in zip(labels,colors): print l,c colordict[l]=c fig = plt.figure(figsize=[10, 10]) ax = fig.add_subplot(111) pie_wedge_collection = ax.pie(slices, labels=labels, labeldistance=1.05)#, autopct=make_autopct(slices)) for pie_wedge in pie_wedge_collection[0]: pie_wedge.set_edgecolor('white') pie_wedge.set_facecolor(colordict[pie_wedge.get_label()]) titlestring = 'Issues' ax.set_title(titlestring) return fig,ax,pie_wedge_collection slices = [37, 39, 39, 38, 62, 21, 15, 9, 6, 7, 6, 5, 4...

Changing The "tick Frequency" On X Or Y Axis In Matplotlib?

Answer : You could explicitly set where you want to tick marks with plt.xticks : plt.xticks(np.arange(min(x), max(x)+1, 1.0)) For example, import numpy as np import matplotlib.pyplot as plt x = [0,5,9,10,15] y = [0,1,2,3,4] plt.plot(x,y) plt.xticks(np.arange(min(x), max(x)+1, 1.0)) plt.show() ( np.arange was used rather than Python's range function just in case min(x) and max(x) are floats instead of ints.) The plt.plot (or ax.plot ) function will automatically set default x and y limits. If you wish to keep those limits, and just change the stepsize of the tick marks, then you could use ax.get_xlim() to discover what limits Matplotlib has already set. start, end = ax.get_xlim() ax.xaxis.set_ticks(np.arange(start, end, stepsize)) The default tick formatter should do a decent job rounding the tick values to a sensible number of significant digits. However, if you wish to have more control over the format, you can define your own formatter. For example...