How to label only certain x-ticks matplotlib? - matplotlib

In this diagram I have distributed the ticks and applied a tick:
ax.set_xticks(np.arange(0, 800, 1))
ax.grid()
How can I label on the x-axis only the numbers present in the legend?
Regards,
Karl

Try this to keep all grid points, but only label the points of interest.
original_labels = [str(label) for label in ax.get_xticks()]
labels_of_interest = [str(i) for i in np.arange(235,295,5)]
new_labels = [label if label in labels_of_interest else "" for label in original_labels]
ax.set_xticklabels(new_labels)
Edit:
an optional parameter to ax.set_xticklabels is rotation. If you find your labels are still overlapping, try rotating them:
ax.set_xticklabels(new_labels, rotation=45) #rotate labels 45 degrees

Related

changing the spacing between tick labels on Matplotlib Heatmap

I am using the following code to generate this heatmap:
h= np.vstack((aug2014, sep2014,oct2014, nov2014, dec2014, jan2015, feb2015, mar2015, apr2015, may2015, jun2015, jul2015, aug2015))
dim = np.arange(1, 32, 1)
fig, ax = plt.subplots(figsize=(9,3))
heatmap = ax.imshow(h, cmap=plt.cm.get_cmap('Blues', 4), aspect=0.5, clim=[1,144])
cbar = fig.colorbar(heatmap, ticks = [1, 36, 72, 108, 144], label = 'Number of valid records per day')
ax.set_xlabel("Days", fontsize=15)
ax.set_ylabel("Months", fontsize=15)
ax.set_title("Number of valid records per day", fontsize=20)
ax.set_xticks(range(0,31))
ax.set_xticklabels(dim, rotation=45, ha='center', minor=False)
ax.set_yticks(range(0,13,1))
ax.set_yticklabels(ylabel[7:20])
ax.grid(which = 'minor', color = 'w')
ax.set_facecolor('gray')
fig.show()
As you can see, the labels on the y-axis are not very readable. I was wondering whether there would be a way for me to either increase the dimension of the grid cell or change the scale on the axis to increase the space between the labels. I have tried changing the figsize but all it did was to make the colorbar much bigger than the heatmap. I also have have two subsidiary questions:
Can someone explain to me why the grid lines do not show on the figure although I have defined them?
How can I increase the font of the colorbar title?
Any help would be welcomed!

enlarge contour plot values on the line

I would like to know if there is a way to enlarge the values on the line in a contour plot. Attached after the code is a link to a contour plot like mine, there are values on the line and I would like to enlarge those numerical values on the contour line.
I enlarged the chart so all the axis and title shrunk, but I managed to enlarge the text for the axis and title. Now I am just having issues enlarging the values on the contour lines themselves. Attached below is a portion of the code I wrote.
plt.figure(figsize=(20,20), dpi=400)
contour_graph = plt.contour(R,h_diam,keff_array)
plt.xlabel('Diameter (cm)', size = 20)
plt.ylabel('Height/Diameter', size = 20)
plt.title('Multiplication Factor for Different Deminsions', size = 40)
plt.xticks(size = 20)
plt.yticks(size = 20)
plt.xlim(0,20)
plt.ylim(0,2)
plt.clabel(contour_graph)
plt.grid()
plt.savefig('contourplotratioVdiam.png')
https://www.google.com/imgres?imgurl=https%3A%2F%2Fdoxdrum.files.wordpress.com%2F2010%2F04%2Fvelocity-add.png&imgrefurl=https%3A%2F%2Fdoxdrum.wordpress.com%2F2010%2F04%2F11%2Fcontour-plot-in-sage-and-matplotlib%2F&docid=pyXslh9eixfe-M&tbnid=8AyQEBR6HwVqYM%3A&vet=10ahUKEwjB28HyopbjAhWNQc0KHcAVBgcQMwipASg6MDo..i&w=600&h=370&bih=754&biw=1536&q=contour%20plot%20python&ved=0ahUKEwjB28HyopbjAhWNQc0KHcAVBgcQMwipASg6MDo&iact=mrc&uact=8
The clabel option accepts fontsize as a parameter to control the size of contour labels. From the docs:
clabel(cs, [levels,] **kwargs)
Adds labels to line contours in cs, where cs is a ContourSet object returned by contour().
Parameters:
fontsize : string or float, optional
Size in points or relative size e.g., 'smaller', 'x-large'. See Text.set_size for accepted string values.
So in your case, you can use
plt.clabel(contour_graph, fontsize=24)

Pandas, Bar Chart Annotations

How to properly give Annotations to Pandas Bar Charts?
I'm following Bar Chart Annotations with Pandas and MPL, but somehow I can't make it into my own code -- this is as far as I can go. What's wrong?
I've also found the following code from here:
def autolabel(rects):
# attach some text labels
for rect in rects:
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width()/2., 1.05*height,
'%d' % int(height),
ha='center', va='bottom')
autolabel(rects1)
autolabel(rects2)
But I don't how to apply that to my code either. Please help.
UPDATE:
Thank you #CT Zhu, for the answer. However, in your horizontal bars, you are still placing the text on top of bars, but I need the text show up within or along them, like this from my referenced article,
where s/he says,
"I am very parital to horizontal bar charts, as I really think they are easier to read, however, I understand that a lot of people would rather see this chart implemented in a regular bar chart. So, here is the code to do that; you will notice that a few things have changed in order to create the annotation"*
It appears your autolabel function is expecting a list of patches, sssuming your plot only those bars as its patches, we could do:
df = pd.DataFrame({'score':np.random.randn(6),
'person':[x*3 for x in list('ABCDEF')]})
def autolabel(rects):
x_pos = [rect.get_x() + rect.get_width()/2. for rect in rects]
y_pos = [rect.get_y() + 1.05*rect.get_height() for rect in rects]
#if height constant: hbars, vbars otherwise
if (np.diff([plt.getp(item, 'width') for item in rects])==0).all():
scores = [plt.getp(item, 'height') for item in rects]
else:
scores = [plt.getp(item, 'width') for item in rects]
# attach some text labels
for rect, x, y, s in zip(rects, x_pos, y_pos, scores):
ax.text(x,
y,
'%s'%s,
ha='center', va='bottom')
ax = df.set_index(['person']).plot(kind='barh', figsize=(10,7),
color=['dodgerblue', 'slategray'], fontsize=13)
ax.set_alpha(0.8)
ax.set_title("BarH")#,fontsize=18)
autolabel(ax.patches)
ax = df.set_index(['person']).plot(kind='bar', figsize=(10,7),
color=['dodgerblue', 'slategray'], fontsize=13)
ax.set_alpha(0.8)
ax.set_title("Bar")#,fontsize=18)
autolabel(ax.patches)

How to shift the colorbar position to right in matplotlib?

I draw a scatter chart as below :
The code is :
sc = plt.scatter(x, y, marker='o', s=size_r, c=clr, vmin=lb, vmax=ub, cmap=mycm, alpha=0.65)
cbar = plt.colorbar(sc, shrink=0.9)
And I want to shift the colorbar to right a little bit to extend the drawing area. How to do that ?
Use the pad attribute.
cbar = plt.colorbar(sc, shrink=0.9, pad = 0.05)
The documentation of make_axes() describes how to use pad: "pad: 0.05 if vertical, 0.15 if horizontal; fraction of original axes between colorbar and new image axes".
Actually you can put the colorbar anywhere you want.
fig1=figure()
sc = plt.scatter(x, y, marker='o', s=size_r, c=clr, vmin=lb, vmax=ub, cmap=mycm, alpha=0.65)
position=fig1.add_axes([0.93,0.1,0.02,0.35]) ## the parameters are the specified position you set
fig1.colorbar(sc,cax=position) ##

small scatter plot markers in matplotlib are always black

I'm trying to use matplotlib to make a scatter plot with very small gray points. Because of the point density, the points need to be small. The problem is that the scatter() function's markers seem to have both a line and a fill. When the markers are small, only the line is visible, not the fill, and the line isn't the right colour (it's always black).
I can get exactly what I want using gnuplot: plot 'nodes' with points pt 0 lc rgb 'gray'
How can I make very small gray points using matplotlib scatterplot()?
scatter([1,2,3], [2,4,5], s=1, facecolor='0.5', lw = 0)
This sets the markersize to 1 (s=1), the facecolor to gray (facecolor='0.5'), and the linewidth to 0 (lw=0).
If the marker has no face (cannot be filled, e.g. '+','x'), then the edgecolor has to be set instead of c, and lw should not be 0:
scatter([1,2,3], [2,4,5], marker='+', edgecolor='r')
The following will no work
scatter([1,2,3], [2,4,5], s=1, marker='+', facecolor='0.5', lw = 0)
because the edge/line will not be displayed, so nothing will be displayed.
The absolute simplest answer to your question is: use the color parameter instead of the c parameter to set the color of the whole marker.
It's easy to see the difference when you compare the results:
from matplotlib import pyplot as plt
plt.scatter([1,2,3], [3,1,2], c='0.8') # marker not all gray
plt.scatter([1,2,3], [3,1,2], color='0.8') # marker all gray
Details:
For your simple use case where you just want to make your whole marker be the same shade of gray color, you really shouldn't have to worry about things like face color vs edge color, and whether your marker is defined as all edges or some edges and some fill. Instead, just use the color parameter and know that your whole marker will be set to the single color that you specify!
In response to zwol's question in comment - my reputation is not high enough to leave comments, so this will have to do: In the event that your colors come from a colormap (i.e., are from a "sequence of values to be mapped") you can use color = as demonstrated in the following:
from matplotlib import pyplot
x = [1,5,8,9,5]
y = [4,2,4,7,9]
numSides = [2,3,1,1,5]
cmap = pyplot.cm.get_cmap("copper_r")
min, max = min(numSides), max(numSides)
for i in range(len(x)):
if numSides[i] >= 2:
cax = pyplot.scatter(x[i], y[i], marker = '+', s = 100, c = numSides[i], cmap = cmap)
cax.set_clim(min, max)
elif numSides[i] == 1:
pyplot.scatter(x[i], y[i], marker = '.', s = 40, color = cmap(numSides[i]))
fig = pyplot.gcf()
fig.set_size_inches(8.4, 6)
fig.savefig('figure_test.png', dpi = 200)
pyplot.show()