ticks format of an axis in matplotlib - python

I'm trying to draw clean graphs using matplotlib.
Here is my code:
fig = plt.figure(figsize = (6,6))
plt.grid(True)
plt.xlabel('time (s)',fontweight='bold')
plt.ylabel('density',fontweight='bold')
plt.plot(data1, data2, color = 'y', linewidth = 2)
plt.show()
the floats in data2 lies between 0.0001 and 0.001, so When I do this, the y axis has ticks like '0.0001' '0.0002' etc.
How can I force the ticks to be in scientific notation ('1e-3', '1e-4' etc. ) ?
thx :)

This sets it like 1e-04:
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
data1 = [1,2,3,4,5]
data2 = [1e4,3e4,4e4,2e4,5e4]
fig = plt.figure(figsize = (6,6))
plt.grid(True)
plt.xlabel('time (s)',fontweight='bold')
plt.ylabel('density',fontweight='bold')
plt.plot(data1, data2, color = 'y', linewidth = 2)
plt.gca().yaxis.set_major_formatter(mtick.FormatStrFormatter('%.0e'))
plt.show()

Related

Python - Matplotlib not showing any axis labels on twin plot

I am unable to see any labels on this plot and I have specified labels for each axis. The same thing is happening with the x axis showing as 0,2,4, rather than 0,1,2,3,4 etc.
For reference - I am using this within my PySimpleGUI code:
import matplotlib.pyplot as plt
data1= [0,1,2,3,4,5,6,7,8,9]
data2= [10,20,30,40,50,60,70,133,121,123]
data3=[100,324,121,432,232,543,332,543,534,122]
data4=[100,312,111,111,322,443,545,122,345,122]
#plt.style.use('dark_background')
title="my graph"
plt.figure(figsize=(8,5))
plt.style.use('ggplot')
plt.rcParams['axes.facecolor'] ='white'
plt.rcParams['font.size'] = '8'
plt.bar(data1,data2, color= 'blue' ,width=0.5,label="data2")
plt.twinx()
plt.plot(data1, data3, label="data 3 label")
plt.plot(data1, data4,label="data4",color='green')
plt.xlabel("my x axis label",fontsize =8)
plt.title(title,fontsize=8)
plt.tight_layout()
fig = plt.gcf()
print(fig)
Please could someone point me in the right direction?
Thank you
Some clean-up using the object-oriented interface:
plt.style.use('ggplot')
plt.rcParams['axes.facecolor'] ='white'
plt.rcParams['font.size'] = '8'
fig, ax = plt.subplots(figsize=(8, 5))
ax.bar(data1,data2, color= 'blue' ,width=0.5,label="data2")
ax2 = ax.twinx()
ax2.plot(data1, data3, label="data 3 label")
ax2.plot(data1, data4,label="data4",color='green')
ax.set_xlabel("my x axis label",fontsize =8)
ax.set_xticks(data1)
ax.set_title(title,fontsize=8)
fig.tight_layout()
Output:
Perhaps better to use MultipleLocator for the tick positions (credit for the idea to #JohanC):
from matplotlib.ticker import MultipleLocator
...
ax.xaxis.set_major_locator(MultipleLocator(1))
Try using plt.axes() to separate it, as shown
import matplotlib.pyplot as plt
data1= [0,1,2,3,4,5,6,7,8,9]
data2= [10,20,30,40,50,60,70,133,121,123]
data3=[100,324,121,432,232,543,332,543,534,122]
data4=[100,312,111,111,322,443,545,122,345,122]
#plt.style.use('dark_background')
title="my graph"
plt.figure(figsize=(8,5))
plt.style.use('ggplot')
plt.rcParams['axes.facecolor'] ='white'
plt.rcParams['font.size'] = '8'
ax = plt.axes()
ax.bar(data1,data2, color= 'blue' ,width=0.5,label="data2")
ax2 = plt.twinx()
ax2.plot(data1, data3, label="data 3 label")
ax2.plot(data1, data4,label="data4",color='green')
ax2.set_xlabel("my x axis label",fontsize =8)
plt.title(title,fontsize=8)
plt.tight_layout()
fig = plt.gcf()
print(fig)

How can I do subplots in matplotlib with differents xlimit and size of axis-x?

How can I solve this? I want to do 4 subplots with matplotlib, I have used the subplot option but the result is just a big plot. I don't have idea what is the problem. I want to see four subplots, each one with title, and a suptitle for them.
I don't have idea how can I solve it?
Can you help me please to fix it?
Thanks a lot
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from matplotlib.collections import LineCollection
import matplotlib.patches as mpatches
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.ticker as tkr
from pylab import text
with open("file1.txt") as f:
m1 = map(float,f)
with open ("file2.txt") as f:
m2 = map(float, f)
fig, ax = plt.subplots(sharey='row')
fig.set_figwidth(18) #Width figure
fig.set_figheight(12) #Height figure
plt.rcParams['figure.dpi'] = 300
plt.subplots_adjust(wspace=0.18, hspace=0.2)
fig.suptitle('PLOTS', y=0.93, fontsize=15)
# Plot
plt.subplot(421)
y = np.array(m1)
x = np.arange(len(y))
threshold = 0.5
segments_x = np.r_[x[0], x[1:-1].repeat(2), x[-1]].reshape(-1, 2)
segments_y = np.r_[y[0], y[1:-1].repeat(2), y[-1]].reshape(-1, 2)
linecolors = ['red' if y_[0] > threshold and y_[1] > threshold else 'blue'
for y_ in segments_y]
segments = [zip(x_, y_) for x_, y_ in zip(segments_x, segments_y)]
ax = plt.axes()
ax.add_collection(LineCollection(segments, colors=linecolors))
ax.set_ylim(-0.06, 1.07)
ax.set_xlim(0,268)
blue_patch = mpatches.Patch(color='blue', label='ordenada')
red_patch = mpatches.Patch(color='red', label='desordenada')
plt.legend(handles=[blue_patch, red_patch], loc='lower left', fontsize=12)
plt.axhline(y=0.5, color='black', linestyle='--')
plt.title(r'Protein', fontsize=18)
plt.xlabel(r'# Residue', fontsize=16)
plt.ylabel(r'(%)', fontsize=16)
plt.xticks(size=12)
plt.yticks(size=12)
plt.xticks(np.arange(min(x), max(x)+1, 10))
plt.grid()
plt.tight_layout()
# Plot
plt.subplot(423)
p = np.array(m2)
o = np.arange(len(p))
threshold = 0.5
segments_o = np.r_[o[0], o[1:-1].repeat(2), o[-1]].reshape(-1, 2)
segments_p = np.r_[p[0], p[1:-1].repeat(2), p[-1]].reshape(-1, 2)
linecolors = ['red' if p_[0] > threshold and p_[1] > threshold else 'blue'
for p_ in segments_p]
segments = [zip(o_, p_) for o_, p_ in zip(segments_o, segments_p)]
ax = plt.axes()
ax.add_collection(LineCollection(segments, colors=linecolors))
ax.set_ylim(-0.06, 1.07)
ax.set_xlim(0,383)
blue_patch = mpatches.Patch(color='blue', label='ordenada')
red_patch = mpatches.Patch(color='red', label='desordenada')
plt.legend(handles=[blue_patch, red_patch], loc='lower left', fontsize=12)
plt.axhline(y=0.5, color='black', linestyle='--')
plt.title(r'Protein', fontsize=18)
plt.xlabel(r'# Residue', fontsize=16)
plt.ylabel(r'(%)', fontsize=16)
plt.xticks(size=12)
plt.yticks(size=12)
plt.xticks(np.arange(min(o), max(o)+1, 10))
plt.grid()
plt.tight_layout()
plt.show()
#plt.savefig('figure.png', format='png', bbox_inches="tight", dpi=300)
How can I solve this?
where is the problem?
You need to specify the number of plots you want to be created by matplotlib.pyplot.subplots,
nrows = 2
ncols = 2
fig, ax = plt.subplots(nrows, ncols, sharey='row')
which will create an array of axes instances with shape (nrows, ncols). You can then plot to individual axes via
ax[0,0].plot(...)
Although in order to set tick properties, labels, etc for the axes you need to use the axes versions of the functions instead of the pyplot versions. I.e.
ax[0, 0].set_xticks(...)
# instead of
plt.xticks(...)
ax[0, 0].set_title(...)
# instead of
plt.title(...)
ax[0, 0].set_xlabel(...)
# instead of
plt.set_xlabel(...)

How to create histogram with multiple arrays with various length, with percentage on y axes with matplotlib

I would like to create histogram plot for multiple arrays, that will have shared percentage y-axis.
For example, this plot correctly:
import numpy as np
from matplotlib import pyplot as plt
import matplotlib.ticker as ticker
# these are my measurements, unsorted
num_of_points = 10000
num_of_bins = 20
data = np.random.randn(num_of_points) # generate random numbers from a gaussian distribution
fig, ax = plt.subplots()
ax.hist(data, bins=num_of_bins, edgecolor='black', alpha=0.3)
ax.set_title("Histogram")
ax.set_xlabel("X axis")
ax.set_ylabel("Percentage")
ax.yaxis.set_major_formatter(ticker.PercentFormatter(xmax=len(data)))
plt.show()
But when I add another data with diffrent lenght, percentage for data2 is off, because PercentFormatter takes len(data).
num_of_points = 10000
num_of_points2 = 30000
num_of_bins = 20
data = np.random.randn(num_of_points) # generate random numbers from a gaussian distribution
data2 = np.random.randn(num_of_points2)
fig, ax = plt.subplots()
ax.hist(data, bins=num_of_bins, edgecolor='black', alpha=0.3)
ax.hist(data2, bins=num_of_bins, edgecolor='black', alpha=0.3)
ax.set_title("Histogram")
ax.set_xlabel("X axis")
ax.set_ylabel("Percentage")
ax.yaxis.set_major_formatter(ticker.PercentFormatter(xmax=len(data2)))
plt.show()
So how can I have shared percentage y-ax, that will be correct for both data arrays?
I think one way to solve this issue would be plotting the second data using the secondary y-axis.
Try this!
import numpy as np
from matplotlib import pyplot as plt
import matplotlib.ticker as ticker
# these are my measurements, unsorted
num_of_points = 10000
num_of_bins = 20
data = np.random.randn(num_of_points) # generate random numbers from a gaussian distribution
fig, ax = plt.subplots()
ax.hist(data, bins=num_of_bins, color='blue', edgecolor='black', alpha=0.1)
ax.set_title("Histogram")
ax.set_xlabel("X axis")
ax.set_ylabel("Percentage of data")
ax.yaxis.set_major_formatter(ticker.PercentFormatter(xmax=len(data)))
ax1 = ax.twinx()
num_of_points2 = 30000
data2 = np.random.randn(num_of_points2)
ax1.hist(data2, bins=num_of_bins, color='orange', edgecolor='black', alpha=0.1)
ax1.set_ylabel("Percentage of data2")
ax1.yaxis.set_major_formatter(ticker.PercentFormatter(xmax=len(data2)))
plt.show()

How do I change the fontsize of the base and exponent on my colorbar?

I'd like to change the size of the base and exponent to match the fontsize of the ticks on my colorbar. How can I do this?
for i in xrange(col):
plt.plot( t, x[i], color = s_m.to_rgba(slopes[i]), linewidth = 3 )
cbar = plt.colorbar(s_m)
cbar.formatter.set_powerlimits((0, 0))
cbar.update_ticks()
cbar.ax.tick_params(labelsize=20)
First off, let's cobble together a stand-alone example to demonstrate your problem. You've changed the size of the colorbar's tick labels, but the offset label didn't update. For example, it would be nice if the text at the top of the colorbar matched the size of the tick labels:
import numpy as np
import matplotlib.pyplot as plt
data = np.random.random((10, 10)) * 1e-6
fig, ax = plt.subplots()
im = ax.imshow(data)
cbar = fig.colorbar(im)
cbar.ax.tick_params(labelsize=20)
ax.set(xticks=[], yticks=[])
plt.show()
What you're wanting to change is referred to as the offset_text. In this case, it's the offset text of the y-axis of the colorbar. You'd want to do something similar to:
cbar.ax.yaxis.get_offset_text.set(size=20)
or
cbar.ax.yaxis.offsetText.set(size=20)
As a complete example:
import numpy as np
import matplotlib.pyplot as plt
data = np.random.random((10, 10)) * 1e-6
fig, ax = plt.subplots()
im = ax.imshow(data)
cbar = fig.colorbar(im)
cbar.ax.tick_params(labelsize=20)
ax.set(xticks=[], yticks=[])
cbar.ax.yaxis.get_offset_text().set(size=20)
plt.show()

How to plot with x-axis at the top of the figure?

I would like to ask how to produce a plot similar to that in the figure below? Basically, how to have x-axis at the top of the figure. Thanks
Image from: http://oceanographyclay1987.blogspot.com/2010/10/light-attenuation-in-ocean.html
Use
ax.xaxis.set_ticks_position("top")
For example,
import numpy as np
import matplotlib.pyplot as plt
numdata = 100
t = np.linspace(0, 100, numdata)
y = 1/t**(1/2.0)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.xaxis.set_ticks_position('top')
ax.yaxis.grid(linestyle = '-', color = 'gray')
ax.invert_yaxis()
ax.plot(t, y, 'g-', linewidth = 1.5)
plt.show()

Categories