How to set ticks on Fixed Position , matplotlib - python

Can anyone help me set the ticks on a fixed position using matplotlib? I've tried using FixedPosition as this tutorial describes:
ax = pl.gca()
ax.xaxis.set_major_locator(eval(locator))
http://scipy-lectures.github.io/intro/matplotlib/matplotlib.html#figures-subplots-axes-and-ticks
But when I try to run, it tells me that set_major_locator method does not exist.
A simple example would be very useful.
Thanks.

Just use ax.set_xticks(positions) or ax.set_yticks(positions).
For example:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.set_xticks([0.15, 0.68, 0.97])
ax.set_yticks([0.2, 0.55, 0.76])
plt.show()

import numpy as np
import matplotlib.ticker as ticker
import matplotlib.pyplot as plt
name_list = ('Omar', 'Serguey', 'Max', 'Zhou', 'Abidin')
value_list = np.random.randint(0, 99, size = len(name_list))
pos_list = np.arange(len(name_list))
ax = plt.axes()
ax.xaxis.set_major_locator(ticker.FixedLocator((pos_list)))
ax.xaxis.set_major_formatter(ticker.FixedFormatter((name_list)))
plt.bar(pos_list, value_list, color = '.75', align = 'center')
plt.show()

Related

How to change the x: and y: when using mplcursor in python

Using a simple code like below, the annotations I get for the cursors are "x:<>, y:<>"
How can I change the code so I see: "xaxis:<>, yaxis:<>"
Also it would help to know how to do this if I have multiple subplots...
enter image description here
import matplotlib.pyplot as plt
import numpy as np
import mplcursors
data = np.outer(range(10), range(1, 5))
fig, ax = plt.subplots()
lines = ax.plot(data)
ax.set_title("Click somewhere on a line.\nRight-click to deselect.\n"
"Annotations can be dragged.")
mplcursors.cursor(lines) # or just mplcursors.cursor()
plt.xlabel('xaxis')
plt.ylabel('ylabel')
plt.show()
You can change the annotation by adding a function to be called when the annotation is activated. Such a function can be in lambda form ("anonymous function"), or a separately written function in Python. When working with subplots, a cursor can be added to each of them.
You can take a look at the examples in the official documentation to get an overview of the possibilities.
import matplotlib.pyplot as plt
import numpy as np
import mplcursors
def annotation_function(sel):
ax = sel.artist.axes
sel.annotation.set_text(
f'{ax.get_xlabel()}: {sel.target[0]:.2f}\n{ax.get_ylabel()}: {sel.target[1]:.2f}')
fig, axs = plt.subplots(nrows=2, ncols=3, figsize=(15, 10))
for i, ax_row in enumerate(axs):
for j, ax in enumerate(ax_row):
data = np.random.normal(0.1, 100, size=(50, 5)).cumsum(axis=0)
lines = ax.plot(data)
ax.set_title(f'Subplot <{i},{j}>')
ax.set_xlabel('x_' + ''.join(np.random.choice([*'ABCDEF'], np.random.randint(3, 8))))
ax.set_ylabel('y_' + ''.join(np.random.choice([*'ABCDEF'], np.random.randint(3, 8))))
cursor = mplcursors.cursor(lines)
cursor.connect('add', annotation_function)
plt.tight_layout()
plt.show()

Filling subplot with colormap - Matplotlib LogNorm does work in python 3 anymore

I had pretty nice plots looking like this created a while ago in python 2.7.
Now it appears that LogNorm does not work anymore.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
fig = plt.figure()
ax = fig.add_subplot(111)
# creating logspaced values for colorbar
x = np.logspace(-8,-3,6)
yarr = np.vstack((x,))
print(yarr)
# check if yarr is really logspaced
ax.plot(yarr, [1e1]*len(yarr), 'w.-')
# fill box with colorbar - this does not work anymore
ax.imshow(yarr, extent=(1e-8, 1e-3, 1, 1e4), norm=LogNorm(vmin=1e-8, vmax=1e-3))
ax.set_xscale("log")
ax.set_yscale("log")
Output now
Thanks in advance.
It was pointed out to me that it is a problem of matplotlib:
https://github.com/matplotlib/matplotlib/issues/7661/
import numpy as np
import matplotlib.pyplot as plt
tmp = np.arange(199).reshape(1, 199)
y = np.logspace(0, -4, 2)
x = np.logspace(-8, -3, 200)
fig, ax = plt.subplots()
ax.set_xscale('log')
ax.set_yscale('log')
ax.pcolormesh(x, y, tmp)
plt.show()
This solves the problem.

How to create specific plots using Pandas and then store them as PNG files?

So I am trying to create histograms for each specific variable in my dataset and then save it as a PNG file.
My code is as follows:
import pandas as pd
import matplotlib.pyplot as plt
x=combined_databook.groupby('x_1').hist()
x.figure.savefig("x.png")
I keep getting "AttributeError: 'Series' object has no attribute 'figure'"
Use matplotlib to create a figure and axis objects, then tell pandas which axes to plot on using the ax argument. Finally, use matplotlib (or the fig) to save the figure.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Sample Data (3 groups, normally distributed)
df = pd.DataFrame({'gp': np.random.choice(list('abc'), 1000),
'data': np.random.normal(0, 1, 1000)})
fig, ax = plt.subplots()
df.groupby('gp').hist(ax=ax, ec='k', grid=False, bins=20, alpha=0.5)
fig.savefig('your_fig.png', dpi=200)
your_fig.png
Instead of using *.hist() I would use matplotlib.pyplot.hist().
Example :
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
y =[10, 20,30,40,100,200,300,400,1000,2000]
x = np.arange(10)
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(x, y, label='$y = Values')
plt.title('my plot')
ax.legend()
plt.show()
fig.savefig('tada.png')

How to remove y axis of a figure with a discontinous x axis?

I am trying to plot a figure (as shown below) with discontinous x axis with the help of brokenaxes module.
https://pypi.org/project/brokenaxes/
But I don't know how to remove y axis in the figure. I tried some approaches from other quesitons, but seems not compatible with brokenaxes module. Anybody can help?
The code is presented here.
import matplotlib.pyplot as plt
from brokenaxes import brokenaxes
import numpy as np
import pandas as pd
fig = plt.figure(figsize=(7,3))
bax = brokenaxes(xlims=((2500, 4000), (600, 1800)), hspace=1000)
p1= pd.read_csv("p1_1.csv", header=None, skiprows=2)
p1=p1.values
p1=p1.transpose()
bax.plot(p1[0], p1[1])
bax.get_xaxis
bax.invert_xaxis()
bax.set_xlabel('Wavenumber ($cm^{-1}$)')
bax.text(0.05, 0.3, "s", fontsize=12)
fig.savefig("1.png", bbox_inches = "tight")
plt.show()
You can access the individual sub-axes create by brokenaxes through the array BrokenAxes.axs[]
for some reason I had to turn the axis invisible and remove the spine as well, but this works:
import matplotlib.pyplot as plt
from brokenaxes import brokenaxes
fig = plt.figure(figsize=(7,3))
bax = brokenaxes(xlims=((2500, 4000), (600, 1800)), hspace=1000)
#p1= pd.read_csv("p1_1.csv", header=None, skiprows=2)
#p1=p1.values
#p1=p1.transpose()
#bax.plot(p1[0], p1[1])
bax.invert_xaxis()
bax.set_xlabel('Wavenumber ($cm^{-1}$)')
bax.text(0.05, 0.3, "s", fontsize=12)
bax.axs[0].get_yaxis().set_visible(False)
bax.axs[0].spines['left'].set_visible(False)
plt.show()
Use the axs propertie of bax:
bax.axs[0].yaxis.set_visible(False)
bax.axs[0].spines['left'].set_visible(False)

Changing number size on Color Map in Python

I'm sure this is probably easy and a simple fix, but I was having a lot of trouble with changing the number sizes on the colormap. Below is the code I have
from matplotlib import cm
import matplotlib.pyplot as plt
from matplotlib.colors import Normalize
cmap = cm.get_cmap('plasma')
fig = plt.figure(figsize=(25,25))
norm = Normalize(vmin=min(dz), vmax=max(dz))
colors = cmap(norm(dz))
sc = cm.ScalarMappable(cmap=cmap,norm=norm)
sc.set_array([])
plt.colorbar(sc)
I am aware on how to change them for the graph with
plt.xticks(size=20)
plt.yticks(size=20)
But just not for the colormap. If anyone can help I would appreciate it.Thank you.
You are looking for the labelsize argument of the tick_params method of the Axes associated to the colorbar. Have a look at the following example:
import matplotlib.pyplot as plt
from numpy.random import default_rng
data = default_rng(0).random((25, 100))
fig, ax = plt.subplots()
ctrf = ax.contourf(data)
cbar = fig.colorbar(ctrf)
cbar.ax.tick_params(labelsize=16)
plt.show()

Categories