enlarge contour plot values on the line - matplotlib

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)

Related

How to label only certain x-ticks 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

Remove the border of a sf polygon when plotted with ggplot2 using geom_sf

I'm working with a shapefile converted from a raster with lots of little holes in it, therefore, the borders create big splodges in the shape when plotted.
I'm currently adding the polygon to the main plot with the below code. Despite setting the alpha value to 1 the colours are different even when both set to "red" which makes no sense to me.
geom_sf(data = filter(db, band == 9), aes(fill = "red"), colour = "red", alpha = 1)
Can I either:
Set the borders to the same colour as the fill?
Or remove the border entirely?
Or set the border colour to none?

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)

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()

matplotlib: Controlling pie chart font color, line width

I'm using some simple matplotlib functions to draw a pie chart:
f = figure(...)
pie(fracs, explode=explode, ...)
However, I couldn't find out how to set a default font color, line color, font size – or pass them to pie(). How is it done?
Showing up a bit late for the party but I encountered this problem and didn't want to alter my rcParams.
You can resize the text for labels or auto-percents by keeping the text returned from creating your pie chart and modifying them appropriately using matplotlib.font_manager.
You can read more about using the matplotlib.font_manager here:
http://matplotlib.sourceforge.net/api/font_manager_api.html
Built in font sizes are listed in the api;
"size: Either an relative value of ‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’ or an absolute font size, e.g. 12"
from matplotlib import pyplot as plt
from matplotlib import font_manager as fm
fig = plt.figure(1, figsize=(6,6))
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
plt.title('Raining Hogs and Dogs')
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
fracs = [15,30,45, 10]
patches, texts, autotexts = ax.pie(fracs, labels=labels, autopct='%1.1f%%')
proptease = fm.FontProperties()
proptease.set_size('xx-small')
plt.setp(autotexts, fontproperties=proptease)
plt.setp(texts, fontproperties=proptease)
plt.show()
Global default colors, line widths, sizes etc, can be adjusted with the rcParams dictionary:
import matplotlib
matplotlib.rcParams['text.color'] = 'r'
matplotlib.rcParams['lines.linewidth'] = 2
A complete list of params can be found here.
You could also adjust the line width after you draw your pie chart:
from matplotlib import pyplot as plt
fig = plt.figure(figsize=(8,8))
pieWedgesCollection = plt.pie([10,20,50,20],labels=("one","two","three","four"),colors=("b","g","r","y"))[0] #returns a list of matplotlib.patches.Wedge objects
pieWedgesCollection[0].set_lw(4) #adjust the line width of the first one.
Unfortunately, I can not figure out a way to adjust the font color or size of the pie chart labels from the pie method or the Wedge object. Looking in the source of axes.py (lines 4606 on matplotlib 99.1) they are created using the Axes.text method. This method can take a color and size argument but this is not currently used. Without editing the source, your only option may be to do it globally as described above.
matplotlib.rcParams['font.size'] = 24
does change the pie chart labels font size