How does matplotlib ensure that a dataset can be within plot with specified size.
How do i from a plot stored as numpy, How do i read the color of the pixels illustration a datapoint (0,4) - in the plot.
example:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from PIL import Image
import librosa
import librosa.display
from matplotlib import cm
fig = plt.figure(figsize=(12,4))
min = -1.828067
max = 22.70058
data = np.random.uniform(low=min, high=max, size=(474,40))
librosa.display.specshow(data.T,sr=16000,x_axis='frames',y_axis='mel',hop_length=160,cmap=cm.jet)
plt.show()
raw_input("sadas")
convert = plt.get_cmap(cm.jet)
numpy_output_static = convert(data.T)
plt.imshow(numpy_output_static, aspect = 'auto')
plt.show()
raw_input("asds")
First plot being :
Second plot being:
so the first has been resized to plot size 12,4 where the last basically plots the same data but just using the data shape as size... how do i change that?
Librosa just performs pcolormesh according to the GitHub source code
You need to define another figure with its own size for the second figure.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from PIL import Image
import librosa
import librosa.display
from matplotlib import cm
fig = plt.figure(figsize=(12,4))
min = -1.828067
max = 22.70058
data = np.random.uniform(low=min, high=max, size=(474,40))
librosa.display.specshow(data.T,sr=16000,x_axis='frames',y_axis='mel',hop_length=160,cmap=cm.jet)
plt.show()
raw_input("sadas")
convert = plt.get_cmap(cm.jet)
numpy_output_static = convert(data.T)
fig = plt.figure(figsize=(12,4))
plt.imshow(numpy_output_static, aspect = 'auto')
plt.show()
raw_input("asds")
Related
The following code display the image and audio in the top-bottom style:
Here is the test code:
import librosa
import matplotlib.pyplot as plt
import IPython.display as ipd
def plot_it(name, audio, sample_rate):
plt.figure(figsize=(8, 1))
plt.plot(audio)
plt.gca().set_title(name)
plt.show()
ipd.display(ipd.Audio(data=audio, rate=sample_rate))
Is it possible for changing the "top-bottom" style to "left-right" style for displaying the audio at the right side of the plt figure?
You can use a GridspecLayout which is similar to matplotlib's GridSpec. In order to direct to output into the needed grid cells, you can capture it using the Output widget:
import librosa
import matplotlib.pyplot as plt
import IPython.display as ipd
from ipywidgets import Output, GridspecLayout
def plot_it(name, audio, sample_rate):
grid = GridspecLayout(1, 2, align_items='center')
out = Output()
with out:
fig, ax = plt.subplots(figsize=(8, 1))
ax.plot(audio)
ax.set_title(name)
plt.close(fig)
ipd.display(ax.figure)
grid[0, 0] = out
out = Output()
with out:
ipd.display(ipd.Audio(data=audio, rate=sample_rate))
grid[0, 1] = out
ipd.display(grid)
name = 'nutcracker'
filename = librosa.example(name)
y, sr = librosa.load(filename)
plot_it(name, y, sr)
(It is essential to close the figure, otherwise you'll have double output of the figure. This is easier to do this using the OOP than the pyplot interface, that's why I changed your matplotlib code a bit)
I'm trying to create a graph with k_b as the x-value and delta_P as the y-value. I want to plot k_b against delta_P but S=3 for one curve and S=0.1 for another curve. However, I want the two lines to be on the same graph. Does anyone have any advice on how to do that? Below is what I have for S=3 and it works.
def rocproduct(k_cat,E0,S,k_b,k_f):
return k_cat*E0*S/((k_b/k_f)+S)
import numpy as np
import matplotlib.pyplot as plt
k_cat=0.1;E0=1;k_f=0.3;S=3
k_b=np.array([0.01,0.1,0.2,0.5,1,1.5,2,5,10])
delta_P=rocproduct(k_cat,E0,S,k_b,k_f)
plt.ylabel('rate of change of product')
plt.xlabel('kb')
plt.plot(k_b,delta_P)
Just call rocproduct for S=0.1 and plot it again
import numpy as np
import matplotlib.pyplot as plt
# Parameters
k_cat=0.1
E0=1
k_f=0.3
S=3
# Function for data
def rocproduct(k_cat,E0,S,k_b,k_f):
return k_cat*E0*S/((k_b/k_f)+S)
# Data to plot
k_b=np.array([0.01,0.1,0.2,0.5,1,1.5,2,5,10])
delta_P_1=rocproduct(k_cat,E0,S,k_b,k_f)
S = 0.1
delta_P_2=rocproduct(k_cat,E0,S,k_b,k_f)
# Plotting
plt.ylabel('rate of change of product')
plt.xlabel('kb')
plt.plot(k_b,delta_P_1)
plt.plot(k_b, delta_P_2)
plt.show()
Im using seaborn to plot an heatmap over an image, the data is a matrix 41x41 on a excel file and the image is 890px by 890px, each value in the matrix contains a value for pollutant concentration, and the image is a map from google earth, but im getting this result. The image is too big for the graph and I dont know how to fit the two together because the plot is always 41px by 41px, how can i do this?
here is the code:
import scipy.misc as sci
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
excel_file = "2002marçoSO2vFINAL1.xls"
xldata = pd.read_excel(excel_file,
sheet_name = "Python")
heatmap_data = xldata
sns.heatmap(heatmap_data, cmap="gist_stern", alpha = 0.2)
img = sci.imread("50x50.png")
plt.imshow(img)
plt.show()```
I am trying to plot 8000 points in three dimensions (x,y,z) of a terrain with matplotlib using the function contourf when I run the code I get the error
'OverflowError: In draw_path_collection: Exceeded cell block limit'
I tried to solve this with "mpl.rcParams['agg.path.chunksize'] = 20000"
but this did not resolve the issue. Here is my code
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from scipy.interpolate import griddata
import pandas as pd
import matplotlib as mpl
datos = pd.read_csv('zrh_terrain.txt', header =0)
dats=500
mpl.rcParams['agg.path.chunksize'] = 20000
X=datos.iloc[0:dats,0].values
Y=datos.iloc[0:dats,1].values
Z=datos.iloc[0:dats,2].values
dt_bar=np.linspace(Z.min(),Z.max(),10)
xi,yi= np.meshgrid(X,Y)
zi = griddata((X,Y),Z,(xi,yi),method='nearest')
plt.contourf(xi,yi,zi,extend='both',vmin=dt_bar[0],vmax=dt_bar[-1],
cmap=cm.terrain)
I have a series of data that I'm reading in from a tutorial site.
I've managed to plot the distribution of the TV column in that data, however I also want to overlay a normal distribution curve with StdDev ticks on a second x-axis (so I can compare the two curves). I'm struggling to work out how to do it..
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as stats
import matplotlib.mlab as mlab
import math
# read data into a DataFrame
data = pd.read_csv('http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv', index_col=0)
# draw distribution curve
h = sorted(data.TV)
hmean = np.mean(h)
hstd = np.std(h)
pdf = stats.norm.pdf(h, hmean, hstd)
plt.plot(h, pdf)
Here is a diagram close to what I'm after, where x is the StdDeviations. All this example needs is a second x axis to show the values of data.TV
Not sure what you really want, but you could probably use second axis like this
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as stats
import matplotlib.mlab as mlab
import math
# read data into a DataFrame
data = pd.read_csv('Advertising.csv', index_col=0)
fig, ax1 = plt.subplots()
# draw distribution curve
h = sorted(data.TV)
ax1.plot(h,'b-')
ax1.set_xlabel('TV')
ax1.set_ylabel('Count', color='b')
for tl in ax1.get_yticklabels():
tl.set_color('b')
hmean = np.mean(h)
hstd = np.std(h)
pdf = stats.norm.pdf(h, hmean, hstd)
ax2 = ax1.twinx()
ax2.plot(h, pdf, 'r.')
ax2.set_ylabel('pdf', color='r')
for tl in ax2.get_yticklabels():
tl.set_color('r')
plt.show()
Ok, assuming that you want to plot the distribution of your data, the fitted normal distribution with two x-axes, one way to achieve this is as follows.
Plot the normalized data together with the standard normal distribution. Then use matplotlib's twiny() to add a second x-axis to the plot. Use the same tick positions as the original x-axis on the second axis, but scale the labels so that you get the corresponding original TV values. The result looks like this:
Code
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as stats
import matplotlib.mlab as mlab
import math
# read data into a DataFrame
data = pd.read_csv('http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv', index_col=0)
h = sorted(data.TV)
hmean = np.mean(h)
hstd = np.std(h)
h_n = (h - hmean) / hstd
pdf = stats.norm.pdf( h_n )
# plot data
f,ax1 = plt.subplots()
ax1.hist( h_n, 20, normed=1 )
ax1.plot( h_n , pdf, lw=3, c='r')
ax1.set_xlim( [h_n.min(), h_n.max()] )
ax1.set_xlabel( r'TV $[\sigma]$' )
ax1.set_ylabel( r'Relative Frequency')
ax2 = ax1.twiny()
ax2.grid( False )
ax2.set_xlim( ax1.get_xlim() )
ax2.set_ylim( ax1.get_ylim() )
ax2.set_xlabel( r'TV' )
ticklocs = ax2.xaxis.get_ticklocs()
ticklocs = [ round( t*hstd + hmean, 2) for t in ticklocs ]
ax2.xaxis.set_ticklabels( map( str, ticklocs ) )