How not to show the intermediate values in matplotlib [duplicate] - 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

Matplotlib imshow ticks are wrong with negative values

import matplotlib.pyplot as plt
import numpy as np
a = np.random.randn(5,5)
plt.imshow(a)
plt.xticks(range(5))
plt.yticks([i-2 for i in range(5)])
plt.show()
results in
??
Also imagine I had 500 instead of 5 ticks, how could I pass the ticks but have less be displayed (for example every 10th)?
Use the extent parameter, and no need to use xticks or yticks:
plt.imshow(a, extent=(-0.5, 4.5, -2.5, 2.5))
Output:
Use MultipleLocator for your second question:
from matplotlib.ticker import MultipleLocator
a = np.random.randn(500,500)
fig, ax = plt.subplots(figsize=(10, 10))
ax.imshow(a, extent=(-0.5, 500.5, -250.5, 250.5))
ax.xaxis.set_major_locator(MultipleLocator(25))
ax.yaxis.set_major_locator(MultipleLocator(25))
Output:

Shrink/adjust the colorbar inside the plot

I am trying to shrink a colorbar, which is positioned inside the plot. When I position it outside of the plot (i. e. pad=0.05), it works just fine.
Here's a MWE:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
z = np.random.random((10,10))
fig, ax = plt.subplots()
ima = ax.matshow(z)
divider = make_axes_locatable(ax)
cb = fig.colorbar(ima, cax=divider.append_axes('right', size="4%", pad=-0.5),shrink=0.75,fraction=0.75)
plt.show()
I have tried both shrink and fraction but none of them seem to do the trick. I am attaching the output. Any help is greatly appreciated!
Your basic problem is that shrink and fraction don't work if you specify cax; it just fills the axes you specify.
I would do this with an inset_axes, where you should play with the positioning to get what you are after:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
z = np.random.random((10,10))
fig, ax = plt.subplots()
ima = ax.matshow(z)
divider = make_axes_locatable(ax)
cb = fig.colorbar(ima, cax=ax.inset_axes((0.9, 0.125, 0.05, 0.75)))
plt.show()

How do I format my y-axis to show a comma separator in my Seaborn graph? [duplicate]

import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import seaborn as sns
import pandas as pd
sns.set(style="darkgrid")
fig, ax = plt.subplots(figsize=(8, 5))
palette = sns.color_palette("bright", 6)
g = sns.scatterplot(ax=ax, x="Area", y="Rent/Sqft", hue="Region", marker='o', data=df, s=100, palette= palette)
g.legend(bbox_to_anchor=(1, 1), ncol=1)
g.set(xlim = (50000,250000))
How can I can change the axis format from a number to custom format? For example, 125000 to 125.00K
IIUC you can format the xticks and set these:
In[60]:
#generate some psuedo data
df = pd.DataFrame({'num':[50000, 75000, 100000, 125000], 'Rent/Sqft':np.random.randn(4), 'Region':list('abcd')})
df
Out[60]:
num Rent/Sqft Region
0 50000 0.109196 a
1 75000 0.566553 b
2 100000 -0.274064 c
3 125000 -0.636492 d
In[61]:
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import seaborn as sns
import pandas as pd
sns.set(style="darkgrid")
fig, ax = plt.subplots(figsize=(8, 5))
palette = sns.color_palette("bright", 4)
g = sns.scatterplot(ax=ax, x="num", y="Rent/Sqft", hue="Region", marker='o', data=df, s=100, palette= palette)
g.legend(bbox_to_anchor=(1, 1), ncol=1)
g.set(xlim = (50000,250000))
xlabels = ['{:,.2f}'.format(x) + 'K' for x in g.get_xticks()/1000]
g.set_xticklabels(xlabels)
Out[61]:
The key bit here is this line:
xlabels = ['{:,.2f}'.format(x) + 'K' for x in g.get_xticks()/1000]
g.set_xticklabels(xlabels)
So this divides all the ticks by 1000 and then formats them and sets the xtick labels
UPDATE
Thanks to #ScottBoston who has suggested a better method:
ax.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: '{:,.2f}'.format(x/1000) + 'K'))
see the docs
The canonical way of formatting the tick labels in the standard units is to use an EngFormatter. There is also an example in the matplotlib docs.
Also see Tick locating and formatting
Here it might look as follows.
import numpy as np; np.random.seed(42)
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import seaborn as sns
import pandas as pd
df = pd.DataFrame({"xaxs" : np.random.randint(50000,250000, size=20),
"yaxs" : np.random.randint(7,15, size=20),
"col" : np.random.choice(list("ABC"), size=20)})
fig, ax = plt.subplots(figsize=(8, 5))
palette = sns.color_palette("bright", 6)
sns.scatterplot(ax=ax, x="xaxs", y="yaxs", hue="col", data=df,
marker='o', s=100, palette="magma")
ax.legend(bbox_to_anchor=(1, 1), ncol=1)
ax.set(xlim = (50000,250000))
ax.xaxis.set_major_formatter(ticker.EngFormatter())
plt.show()
Using Seaborn without importing matplotlib:
import seaborn as sns
sns.set()
chart = sns.relplot(x="x_val", y="y_val", kind="line", data=my_data)
ticks = chart.axes[0][0].get_xticks()
xlabels = ['$' + '{:,.0f}'.format(x) for x in ticks]
chart.set_xticklabels(xlabels)
chart.fig
Thank you to EdChum's answer above for getting me 90% there.
Here's how I'm solving this: (similar to ScottBoston)
from matplotlib.ticker import FuncFormatter
f = lambda x, pos: f'{x/10**3:,.0f}K'
ax.xaxis.set_major_formatter(FuncFormatter(f))
We could used the APIs: ax.get_xticklabels() , get_text() and ax.set_xticklabels do it.
e.g,
xlabels = ['{:.2f}k'.format(float(x.get_text().replace('−', '-')))/1000 for x in g.get_xticklabels()]
g.set_xticklabels(xlabels)

Show mean in the box plot in python?

I am new to Matplotlib, and as I am learning how to draw box plot in python, I was wondering if there is a way to show mean in the box plots?
Below is my code..
from pylab import *
import matplotlib.pyplot as plt
data1=np.random.rand(100,1)
data2=np.random.rand(100,1)
data_to_plot=[data1,data2]
#Create a figure instance
fig = plt.figure(1, figsize=(9, 6))
# Create an axes instance
axes = fig.add_subplot(111)
# Create the boxplot
bp = axes.boxplot(data_to_plot,**showmeans=True**)
Even though I have showmean flag on, it gives me the following error.
TypeError: boxplot() got an unexpected keyword argument 'showmeans'
This is a minimal example and produces the desired result:
import matplotlib.pyplot as plt
import numpy as np
data_to_plot = np.random.rand(100,5)
fig = plt.figure(1, figsize=(9, 6))
ax = fig.add_subplot(111)
bp = ax.boxplot(data_to_plot, showmeans=True)
plt.show()
EDIT:
If you want to achieve the same with matplotlib version 1.3.1 you'll have to plot the means manually. This is an example of how to do it:
import matplotlib.pyplot as plt
import numpy as np
data_to_plot = np.random.rand(100,5)
positions = np.arange(5) + 1
fig, ax = plt.subplots(1,2, figsize=(9,4))
# matplotlib > 1.4
bp = ax[0].boxplot(data_to_plot, positions=positions, showmeans=True)
ax[0].set_title("Using showmeans")
#matpltolib < 1.4
bp = ax[1].boxplot(data_to_plot, positions=positions)
means = [np.mean(data) for data in data_to_plot.T]
ax[1].plot(positions, means, 'rs')
ax[1].set_title("Plotting means manually")
plt.show()
Result:
You could also upgrade the matplotlib:
pip2 install matplotlib --upgrade
and then
bp = axes.boxplot(data_to_plot,showmeans=True)

How can I have one annotation pointing to several points in matplotlib?

I have some data that I usually plot in matplotlib. Certain values of the independent variable are resonances, and I want to label them with something resembling matplotlib's annotate. Is there a way to have one annotation (one balloon that says something like "resonances") with arrows that point to several points on the plot?
In this form is better to you?
import matplotlib.pyplot as plt
import numpy as np
a = np.ones(100)
multi = np.arange(0,100,5)
plt.ylim(-0.5,10)
plt.text(50, 6.5,'a=5k',fontsize=20)
for x in multi:
plt.annotate("",xy=(x,1),xytext=(50,6),
arrowprops=dict(facecolor='black', shrink=0.005))
plt.plot(a,'k.')
plt.show()
how about (basically ripped out of the docs http://matplotlib.org/users/annotations_intro.html)
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line, = ax.plot(t, s, lw=2)
coords_to_annote = [(2,1),(3,1),(4,1)]
for coords in coords_to_annote:
ax.annotate('local max', xy=coords, xytext=(3, 1.5),
arrowprops=dict(facecolor='black', shrink=0.05),
)
ax.set_ylim(-2,2)
plt.show()
You are looking for some similar to?
import matplotlib.pyplot as plt
import numpy as np
a = np.ones(100)
multi = np.arange(0,100,5)
plt.ylim(-0.5,10)
for x in multi:
plt.annotate("a=5k",xy=(x,1),xytext=(x,1+4*np.random.rand()),
arrowprops=dict(facecolor='black', shrink=0.05))
plt.plot(a,'k.')
plt.show()

Categories

Resources