The stackplot function from Matplotlib library can be used as follows :
import matplotlib.pyplot as plt
import numpy as np
import numpy.random as npr
x = np.linspace(0,10,50)
y = [npr.rand(50) for i in range(4)]
plt.stackplot(x,y)
plt.show()
I need to use PyQtGraph library for a project :
import pyqtgraph as pg
from pyqtgraph.Qt import QtGui
import numpy as np
import numpy.random as npr
x = np.linspace(0,10,50)
y = [npr.rand(50) for i in range(4)]
win = pg.GraphicsWindow()
graph = win.addPlot()
#stackplot function
QtGui.QApplication.instance().exec_()
How can I get a stackplot?
Pyqtgraph does not have a built-in stack plot feature, but you could write this yourself just by summing up the plot data before each line to be stacked, and using PlotCurveItem's fillLevel and fillBrush arguments. Example:
import pyqtgraph as pg
import numpy as np
data = np.random.normal(size=(7,10), scale=0.1, loc=1)
stacked = np.cumsum(data, axis=0)
plt = pg.plot()
for i,row in enumerate(stacked):
curve = plt.plot(row, fillLevel=0, fillBrush=(i,10))
curve.setZValue(10-i)
Related
I create a mask of my dataset for plotting only No Animals materials, and when I draw this mask I have problems with the legends, because only the first material defines me and I don't know how to add the other 2 materials.
import numpy as np
import umap
import umap.plot
import pandas as pd
import matplotlib.pyplot as plt
from IPython.display import display,HTML
import cufflinks as cf
cf.set_config_file(sharing='public',theme='ggplot',offline=True)
import seaborn as sns
palpations = np.load('big_matrix_16384.npz',allow_pickle=True)
X = palpations['arr_0']
embedding = umap.UMAP(n_neighbors=50,
min_dist=0.2,
metric='correlation').fit(X)
emb = embedding.transform(X)
mask_1 = Data["Tipo"]=="Animal"
emb_tipo_1 = emb[mask_1]
cmap = plt.cm.Spectral
c =[sns.color_palette("Set2")[x] for x in data_tipo_1.Material.map({"bone":0, "cartilage":1, "liver_raw_piece1":2})]
plt.scatter(emb_tipo_1[:,0],
emb_tipo_1[:,1],
c=c,
label=np.unique(data_tipo_1.Material),s=10)
plt.gca().set_aspect("equal","datalim")
plt.title("UMAP muestras Animales.")
plt.legend()
enter image description here
Code Output Image
Desired Image
[
My CSV data consists of X axis value, Y axis value and Hardness value and I wanted to plot smooth heat map rather than in boxes like.
DATA:
import cv2
from skimage.io import imread, imshow
from skimage.transform import resize
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import glob
import os
from tqdm import tqdm
import pandas as pd
import seaborn as sns
from sklearn.neighbors import KernelDensity
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import style
from astropy.convolution import convolve, Gaussian2DKernel
from scipy.ndimage.filters import gaussian_filter
path = r"C:\Users\patels\Desktop\Ti/"
ids = os.listdir(path)
#print(ids)
for n, id_ in tqdm(enumerate(ids), total=len(ids)):
data = pd.read_excel(path+id_)
print(path+id_)
df1 = data[['HV 0.2', 'X pos. [mm]', 'Y pos. [mm]']]
heatmap1_data = pd.pivot_table(df1, values='HV 0.2', index=['Y pos. [mm]'], columns='X pos. [mm]')
plt.figure() #this creates a new figure on which your plot will appear
heatmap1 = sns.heatmap(heatmap1_data, cmap="viridis", vmin=300, vmax=400)
plt.title(ids[n]+'Ti Hardness Map')
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")
I created the following test code, and the code runs fine. But the plot does not appear when executed. Did I miss something? I use pyplot to create the plots. When I use plt.savefig("test.png") the chart is created and saved.
import numpy
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
from studentRegression import studentReg
from class_vis import prettyPicture, output_image
from ages_net_worth import ageNetWorthData
ages_train, ages_test, net_worths_train, net_worth_test = ageNetWorthData()
plt.clf()
plt.scatter(ages_train, net_worths_train, color="b", label="train data")
plt.legend(loc=2)
plt.xlabel("ages")
plt.ylabel("net worths")
plt.show()
def ageNetWorthData():
random.seed(42)
numpy.random.seed(42)
ages = []
for ii in range(100):
ages.append( random.randint(20,65) )
net_worths = [ii * 6.25 + numpy.random.normal(scale=40.) for ii in ages]
### need massage list into a 2d numpy array to get it to work in LinearRegression
ages = numpy.reshape( numpy.array(ages), (len(ages), 1))
net_worths = numpy.reshape( numpy.array(net_worths), (len(net_worths), 1))
from sklearn.cross_validation import train_test_split
ages_train, ages_test, net_worths_train, net_worths_test = train_test_split(ages, net_worths)
return ages_train, ages_test, net_worths_train, net_worths_test
You are using a "non-interactive" backend (agg). Just remove the line:
matplotlib.use('agg')
You can check the docs here.
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import numpy as np
import matplotlib as mpl
import seaborn as sns
from scipy.stats import gaussian_kde
from numpy import linspace,hstack
LINE_WIDTH = 3
filename=('')
data=[ map(float, line.split()) for line in open(filename,'r') if line.strip()]
dataM=np.array(data)
meandata=np.mean(dataM,axis=0)
SD = np.std(dataM,axis=0)
sns.set_palette("hls")
mpl.rc("figure", figsize=(8, 4))
xs = np.linspace(meandata[0]-(4 * SD[0]) ,meandata[0]+( 4 * SD[0]), dataM[:,0].size)
ys=dataM[:,0]
n,bins,patches=plt.hist(ys,15)
I get this plot.
and I want to get a kernel gaussian distribution plotted over my histogram but I am getting an error TypeError: 'module' object is not callable
When I am trying to do this
my_pdf = gaussian_kde(ys)
x = linspace(30,100,1000)
plt(x,my_pdf(x),'r') # distribution function
plt.hist(ys,normed=1,alpha=.3) # histogram
plt.show()
What am I doing wrong?
You can do this directly using seaborn. It would be something like this:
import pandas as pd
import seaborn as sns
import scipy.stats
import matplotlib.pyplot as plt
data = pd.read_csv('input.txt')
sns.distplot(data, kde=False, fit=scipy.stats.norm)
plt.show()
For a kde plot just do:
sns.distplot(data);