Axis labelling with matplotlib too sparse - python

Matplotlib tries to label the ticks on this x-axis intelligently, but it is a little too sparse. There should be a label for 0 and maybe one for 10 and 100.
This is the code which produces the figure. How can I make the labelling on the x-axis more verbose?
def timePlot2(data, saveto=None, leg=None, annotate=False, limits=timeLimits, labelColumn="# Threads", valueColumn="Average (s)", size=screenMedium):
labels = list(data[labelColumn])
figure(figsize=size)
ax = gca()
ax.grid(True)
xi = range(len(labels))
rts = data[valueColumn] # running time in seconds
ax.scatter(rts, xi, color='r')
if annotate:
for i,j in zip(rts, xi):
ax.annotate("%0.2f" % i, xy=(i,j), xytext=(7,0), textcoords="offset points")
ax.set_yticks(range(len(labels)))
ax.set_yticklabels(labels)
ax.set_xscale('log')
plt.xlim(limits)
if leg:
legend(leg, loc="upper left", fontsize=10)
else:
legend([r"$t$"], fontsize=10)
plt.draw()
if saveto:
plt.savefig(saveto, transparent=True, bbox_inches="tight")

You can define your own X-Axis-Ticks together with their labels using ax.set_xticks(), in your example
ax.set_xticks((10,100,1000))
should do the trick.
If you like to keep the 10^x-labels, you can add the labels explicitly:
ax.set_xticks((10,100,1000),('$10^1$','$10^2$','$10^3$'))

Related

xticks and bins won't match each other - matplotlib.hist

i'm trying to create simple hist plot, using plt.hist. I encountered a strange problem, as you can see in the figure - the bins just overlap each other.
Here is my code:
intervals = np.arange(0.5,max(data)+0.5, .5)
data = np.array(data)
# build labels list
labels = [ str(intervals[i])+'-'+str(intervals[i+1]) for i in range(len(intervals)-1) ]
labels.append(str(max(intervals))+'-'+str(max(intervals)+.5))
# plot
fig, ax = plt.subplots(figsize=(12, 9))
plt.hist(x=data, bins=intervals, width=1)
ax.set_xticks(range(len(intervals)))
ax.set_xticklabels(labels=labels, rotation=45, fontsize=12)
ax.set_title("Max wind speed ~24hr before dust emission ("+loc+")", fontsize=18)
ax.set_xlabel('Wind Speed [m/s]', fontsize=14)
ax.set_ylabel('No. of Events', fontsize=14)
plt.grid(True)
plt.tight_layout()
plt.savefig('th_hist'+loc+'.png')
plt.show()
`
I tried to change the axis size, and also played with the width value.

y-axis range is not logical (matplotlib python)

I just specify the x and y axis limitations but the numbers' order is wrong. how can I fix this?
here is my code:
fig, ax = plt.subplots(figsize=(20,10))
ax.plot(df.finish_price, label="Stock Values", color = 'blue')
plt.ylabel("Price", color='b')
# Generate a new Axes instance, on the twin-X axes (same position)
ax2 = ax.twinx()
ax2.plot(df.sentiment, label= 'Sentiment', color='green')
ax2.tick_params(axis='y', labelcolor='green')
plt.ylim(bottom = -1)
plt.ylim(top=1)
plt.xlabel("Days")
plt.ylabel("Sentiment", color='g')
fig.legend()
plt.show()
and here is the result:
as you can see the numbers' order on the right y-axis is wrong.

Plotting Points on Matplotlib Colored Grid

I am working with the matplotlib library to generate colored graphs which need to have specific points overlayed on top of them. After messing around with matplotlib, I came up with a method to properly color my grid, however I am unable to plot points manually.
def generate_grid(x, y, data):
fig, ax = plt.subplots(1, 1, tight_layout=True)
my_cmap = matplotlib.colors.ListedColormap(['grey'])
my_cmap.set_bad(color='w', alpha=0)
for x in range(x + 1):
ax.axhline(x, lw=2, color='k', zorder=5)
for y in range(y+1):
ax.axvline(y, lw=2, color='k', zorder=5)
ax.imshow(data, interpolation='none', cmap=my_cmap,
extent=[0, y, 0, x], zorder=0)
plt.locator_params(axis="x", nbins=x+1)
plt.locator_params(axis="y", nbins=y+1)
locs, labels = plt.xticks()
labels = [int(item)+1 for item in locs]
plt.xticks(locs, labels)
locs, labels = plt.yticks()
z = len(locs)
labels = [z-int(item) for item in locs]
plt.yticks(locs, labels)
ax.xaxis.tick_top()
plt.show()
How would I go about plotting a point at any given location ie at (4,2) or (2,1)?
You may simply use the scatter method from within your generate_grid function, for instance, immediately before plt.show().
However, note that if you simply use ax.scatter(2,1, s=50) the symbol will end up under your grid.
You need to play with the zorder parameter to ensure that it appears over the grid. For instance ax.scatter(2,1, s=50, zorder=50) did the trick for me:

How to move specific x-axis (minor) tick labels to the top of a figure in matplotlib?

I want to keep the major tick labels, that matplotlib has automatically generated, in their default position under the figure. However, I myself added some minor ticks (with vertical lines) at specific x values, but their labels don't fit between the default major ticks. How can I move these labels to the top of the figure?
My code for reference:
meta = comparisons['meta']
lagsAnycast = np.array(meta['lagsAnycast'])
lagsPenultimate = np.array(meta['lagsPenultimate'])
avgLagAnycast = meta['avgLagAnycast']
avgLagPenultimate = meta['avgLagPenultimate']
plt.step(lagsAnycast, (np.arange(lagsAnycast.size) + 1)/lagsAnycast.size, color='k', label='to anycast IPs', linewidth=1.5)
plt.step(lagsPenultimate, (np.arange(lagsPenultimate.size) + 1)/lagsPenultimate.size, color='k', label='to penultimate IPs', linewidth=1)
plt.axvline(round(avgLagAnycast,1), ls="dashed", color="k", label="average lag to anycast IPs", linewidth=1.5)
plt.axvline(round(avgLagPenultimate,1), ls="dashed", label="average lag to penultimate IPs", color="k", linewidth=1)
plt.axis([-0.34,60,0.7,1])
plt.xlabel("Lag (ms)")
plt.ylabel("CDF")
existingTicks = (plt.xticks())[0][1:].tolist()
plt.gca().xaxis.grid(True, which='major')
plt.gca().xaxis.grid(False, which='minor')
plt.gca().tick_params(axis="x", which="minor", direction="out", top=True)
plt.gca().set_xticks([round(avgLagAnycast,1), round(avgLagPenultimate,1)], minor=True)
plt.legend(loc='right', fontsize=10)
plt.grid(True, ls="dotted")
majorFormatter = FormatStrFormatter('%g')
plt.gca().xaxis.set_major_formatter(majorFormatter)
plt.savefig(os.path.join(os.getcwd(), "datasets/plots/CDF1.png"))
You can use Locators and Formatters to set the ticks and ticklabels and turn them on or off using tick_params:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
x = np.linspace(-3,3)
plt.plot(x, np.sin(x))
ticks = [-np.pi/2,np.pi/2.]
labels = [r"$-\frac{\pi}{2}$",r"$\frac{\pi}{2}$"]
ax = plt.gca()
ax.xaxis.set_minor_locator(ticker.FixedLocator(ticks))
ax.xaxis.set_minor_formatter(ticker.FixedFormatter(labels))
# Set visibility of ticks & tick labels
ax.tick_params(axis="x", which="minor", direction="out",
top=True, labeltop=True, bottom=False, labelbottom=False)
plt.show()

How to display all label values in matplotlib

I have two lists, when I plot with the following code, the x axis only shows up to 12 (max is 15). May I know how can I show all of the values in x list to the x axis? Thanks in advance.
x = [4,5,6,7,8,9,10,11,12,13,14,15,0,1,2,3]
y = [10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,160]
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(np.arange(len(x)), y, 'o')
ax1.set_xticklabels(x)
plt.show()
If I set minor=True in the set_xticklabels function, it shows me all x=2,4,6,8,..,16... but I want ALL values.
P.S. My x axis is not sorted, should display as it shows.
The issue here is that the number of ticks -set automatically - isn’t the same as the number of points in your plot.
To resolve this, set the number of ticks:
ax1.set_xticks(np.arange(len(x)))
Before the ax1.set_xticklabels(x) call.
or better
ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
ax.yaxis.set_major_locator(ticker.MultipleLocator(1))
from other answers in SO
from matplotlib import ticker
import numpy as np
labels = [
"tench",
"English springer",
"cassette player",
"chain saw",
"church",
"French horn",
"garbage truck",
"gas pump",
"golf ball",
"parachute",
]
fig = plt.figure()
ax = fig.add_subplot(111)
plt.title('Confusion Matrix', fontsize=18)
data = np.random.random((10,10))
ax.matshow(data, cmap=plt.cm.Blues, alpha=0.7)
ax.set_xticklabels([''] + labels,rotation=90)
ax.set_yticklabels([''] + labels)
ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
ax.yaxis.set_major_locator(ticker.MultipleLocator(1))
for i in range(data.shape[0]):
for j in range(data.shape[1]):
ax.text(x=j, y=i,s=int(data[i, j]), va='center', ha='center', size='xx-small')
plt.xlabel('Predicted')
plt.ylabel('True')
plt.show()

Categories