How to add grid graph as a background of one graph plot? - python

I want to add grid graph as a background of a signal plot generated from the following code?
dff = pd.read_csv("abc.csv")
x = dff['A']
times = np.arange(len(x))/360
plt.subplot(121)
plt.plot(times, x)
plt.tight_layout()
plt.show()
What should I change in this code. Can anyone help me out.Thanks in advance!

To add gridlines to PyPlot plots, you can use the grid() tool:
import matplotlib.pyplot as plt
plt.subplot(121)
plt.plot()
plt.tight_layout()
plt.grid(axis='both')
plt.show()
You can see more about its arguments here.
Note that in matplotlib you might have a better time using figures with the "axes" object, rather than the functional interface. E.g.:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot()
ax.grid()
This allows you to index axs objects like lists, and pass plots as arguments.

Related

Removing legend from mpl parallel coordinates plot?

I have a parallel coordinates plot with lots of data points so I'm trying to use a continuous colour bar to represent that, which I think I have worked out. However, I haven't been able to remove the default key that is put in when creating the plot, which is very long and hinders readability. Is there a way to remove this table to make the graph much easier to read?
This is the code I'm currently using to generate the parallel coordinates plot:
parallel_coordinates(data[[' male_le','
female_le','diet','activity','obese_perc','median_income']],'median_income',colormap = 'rainbow',
alpha = 0.5)
fig, ax = plt.subplots(figsize=(6, 1))
fig.subplots_adjust(bottom=0.5)
cmap = mpl.cm.rainbow
bounds = [0.00,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0]
norm = mpl.colors.BoundaryNorm(bounds, cmap.N,)
plt.colorbar(mpl.cm.ScalarMappable(norm = norm, cmap=cmap),cax = ax, orientation = 'horizontal',
label = 'normalised median income', alpha = 0.5)
plt.show()
Current Output:
I want my legend to be represented as a color bar, like this:
Any help would be greatly appreciated. Thanks.
You can use ax.legend_.remove() to remove the legend.
The cax parameter of plt.colorbar indicates the subplot where to put the colorbar. If you leave it out, matplotlib will create a new subplot, "stealing" space from the current subplot (subplots are often referenced to by ax in matplotlib). So, here leaving out cax (adding ax=ax isn't necessary, as here ax is the current subplot) will create the desired colorbar.
The code below uses seaborn's penguin dataset to create a standalone example.
import matplotlib.pyplot as plt
import matplotlib as mpl
import seaborn as sns
import numpy as np
from pandas.plotting import parallel_coordinates
penguins = sns.load_dataset('penguins')
fig, ax = plt.subplots(figsize=(10, 4))
cmap = plt.get_cmap('rainbow')
bounds = np.arange(penguins['body_mass_g'].min(), penguins['body_mass_g'].max() + 200, 200)
norm = mpl.colors.BoundaryNorm(bounds, 256)
penguins = penguins.dropna(subset=['body_mass_g'])
parallel_coordinates(penguins[['bill_length_mm', 'bill_depth_mm', 'flipper_length_mm', 'body_mass_g']],
'body_mass_g', colormap=cmap, alpha=0.5, ax=ax)
ax.legend_.remove()
plt.colorbar(mpl.cm.ScalarMappable(norm=norm, cmap=cmap),
ax=ax, orientation='horizontal', label='body mass', alpha=0.5)
plt.show()

How to overlay plots in python with matplotlib

I'm using two related packages that generate plots I want to overlay for comparison. I call a method called plot_spectro from each package which plots to plt. Then I must do plt.legend() and plt.show() to see them. What happens is two plots with the same data ranges appear, but I would like to overlay (superimpose) them.
import matplotlib.pyplot as plt
s.plot_spectro(xaxis=x, yaxis=y)
plt.xlim(-6,2)
plt.ylim(-2.5,2.5)
o1.plot_spectro(xaxis=x, yaxis=y, color='b')
plt.xlim(-6,2)
plt.ylim(-2.5,2.5)
plt.legend()
plt.show()
Create an axis instance and pass it to both the plots as shown below
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
s.plot_spectro(xaxis=x, yaxis=y, ax=ax) # <--- pass ax=ax here
o1.plot_spectro(xaxis=x, yaxis=y, color='b', ax=ax) # <--- pass ax=ax here
plt.xlim(-6,2)
plt.ylim(-2.5,2.5)
plt.legend()
plt.show()

How do I add a colorbar with log data in an image/matrix

I have a 2D matrix I want to plot. The plotting itself works, but I need
a colorbar with it. The figure only makes sense when the data is
log-tranformed. And I want the colorbar show the original values. How
do I do this?
A search provided
A logarithmic colorbar in matplotlib scatter plot
but I cannot make this work.
The code below gives an idea of what I attempt to do. Only the revevant
lines are included (as far as I could see).
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np
my_speed=np.ones(shape=(no,no))
fig=plt.figure(2)
ax=fig.add_subplot(1,1,1)
my_speed=np.log10(my_speed)
ax.imshow(my_speed, interpolation='bilinear', cmap=cm.jet)
plt.colorbar() #this does not work
plt.savefig('myspeedplot.png')
plt.close(2)
Thank you for any help
The idea is not to transform your data, but let the visualization do the trick for you.
pylot.imshow[1] has an optional parameter norm that can do the log transformation for you.
my_speed=np.ones(shape=(no,no))
fig = plt.figure(2)
ax = fig.add_subplot(1,1,1)
# my_speed=np.log10(my_speed)
img = ax.imshow(my_speed, interpolation='bilinear', cmap=cm.jet,
norm=mpl.colors.LogNorm())
fig.colorbar(img)
As far as I see, there are two problems with your code.
First, you are trying to have the ticks on colorbar show original values. For this you should not transform the data, but just normalize the plot.
And second, you are using the ax.imshow and this is why the colorbar does not see it. You should use plt.imshow or use im=ax.imshow and then colorbar(im)
Here is a working solution:
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
my_speed = np.random.rand(20, 20)
fig = plt.figure(2)
ax = fig.add_subplot(1, 1, 1)
im = ax.imshow(my_speed, interpolation='bilinear',
norm=mpl.colors.LogNorm(),
cmap=plt.cm.jet)
cb = plt.colorbar(im, orientation='vertical')
plt.show()

Matplotlib: Plotting two graphs within a specified x-axis range

Basically I'm in a situation where I want to lock down the starting point of the graph depending on the first graph that's plotted.
e.g. If i do something like this.
import matplotlib.pyplot as plt
plt.plot([7,8,9,10], [1,4,9,16], 'yo')
plt.plot([1,9,11,12], [1,4,9,16], 'ro')
plt.show()
I would like a way to restrict the x-axis to start from 7 so (1,1) from the second plot will be removed.
Is there a way to do this? I could keep track of it myself but just curious if there's something built in to handle this.
Thanks.
Matplotlib offers you two ways:
import matplotlib.pyplot as plt
plt.plot([7,8,9,10], [1,4,9,16], 'yo')
plt.plot([1,9,11,12], [1,4,9,16], 'ro')
plt.xlim(xmin=7)
plt.show()
or the more object-oriented way
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([7,8,9,10], [1,4,9,16], 'yo')
ax.plot([1,9,11,12], [1,4,9,16], 'ro')
ax.set_xlim(xmin=7)
plt.show()
If you don't use IPython, I highly recommend it since you can create the axes object and then type ax.<Tab> and see all of your options. Autocomplete can be a wonderful thing in this case.
You can turn auto-scaling off after the first plot (doc):
ax = plt.gca()
ax.autoscale(enable=False)
which will lock down all of the scales (you can do x and y separately as well).
In short: plt.xlim().
In long:
import matplotlib.pyplot as plt
x1, y1 = ([7,8,9,10], [1,4,9,16])
plt.plot(x1, y1, 'yo')
plt.xlim(min(x1), max(x1))
plt.plot([1,9,11,12], [1,4,9,16], 'ro')
plt.show()

matplotlib share x axis but don't show x axis tick labels for both, just one

I'm using python + matplotlib and I'm having two plots share an axis. If you try to set graph1.set_xticklabels([]) while sharing an axis, it has no effect because it is shared. Is there a way to share the axis AND be able to hide the x axis of one plot?
This is a common gotcha when using shared axes.
Fortunately, there's a simple fix: use plt.setp(ax.get_xticklabels(), visible=False) to make the labels invisible on just one axis.
This is equivalent to [label.set_visible(False) for label in ax.get_xticklabels()], for whatever it's worth. setp will automatically operate on an iterable of matplotlib objects, as well as individual objects.
As an example:
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax1.plot(range(10), 'b-')
ax2 = fig.add_subplot(2,1,2, sharex=ax1)
ax2.plot(range(10), 'r-')
plt.setp(ax1.get_xticklabels(), visible=False)
plt.show()
Per a thread on matplotlib-users, you could use
import matplotlib.pyplot as plt
for ax in plt.gcf().axes:
try:
ax.label_outer()
except:
pass
You could use Axes.tick_params():
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212, sharex=ax1)
ax1.tick_params(labelbottom=False)
You can share the axes during subplot creation with plt.subplots as
fig, axes = plt.subplots(nrows=2, sharex=True)
This will automatically turn the ticklabels for inner axes off.
Complete example:
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=2, sharex=True)
axes[0].plot([1,2,3])
axes[1].plot([3,2,1])
plt.show()
Unfortunately, I am not allowed to comment on esmit's answer (which is the best solution in my opinion, thanks esmit), so I have to write my comment as a new answer: I put his solution into a simple function
def remove_inner_ticklabels(fig):
for ax in fig.axes:
try:
ax.label_outer()
except:
pass
which you can call before plt.show(). Joe Kington's answer did not work for me for some reason.

Categories

Resources