I'm trying to create histogram with the below values. This is the JSON format they are being parsed in, which I now want to visualise.
import json, requests
import matplotlib.pyplot as plt
import numpy as np
a = [[{"Name": "A"},{"Value":100}], [{"Name": "B"},{"Value":300}]]
Should I be converting to dictionary first? I want a histogram showing A:100, B:300.
Thanks
Take every pair and make a dictionary out of it. Then, make your histogram. Remember to use xticklabels.
Related
I'm using the following code to slice a 3D image:
import nibabel as nib
import numpy as np
from nibabel.testing import data_path
import os
vol1= np.load("teste01.npy")
zSlice= (vol1[200, :, :]).squeeze()
print (zSlice.shape)
np.save("D:/Volumes convertidos LIDC/slice200.npy", zSlice)
The problem is that I need to do it manually, I need to obtain all slices and there are just to many for it to be possible to keep doing it like that. Is there any alternative?
If I understand correctly what you want to do, the following should work:
for i, s in enumerate(vol1):
np.save(f"D:/Volumes convertidos LIDC/slice{i}.npy", s)
This will save each 2-dimensional slice taken along the 0-th axis in a separate file (which can mean a lot of files)
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
fig,ax=plt.subplots(2,2,figsize=(15,10))
x=np.linspace(-3,3)
ax[0,0].plot(x,foo-function)
now I need a way to save each of the 4 plots into one file like this:
plt1=topleft_plot.saveNOTfigBUTplot('quadfunction.pdf')
how?
Using the answer here: https://stackoverflow.com/a/4328608/16299117
We can do the following to save a SINGLE subplot from the overall figure:
import matplotlib.pyplot as plt
import numpy as np
fig,ax=plt.subplots(2,2,figsize=(15,10))
x=np.linspace(-3,3)
ax[0,0].plot(x,x**2) # This is just to make an actual plot.
# I am not using jupyter notebook, so I use this to show it instead of %inline
plt.show()
# Getting only the axes specified by ax[0,0]
extent = ax[0,0].get_window_extent().transformed(fig.dpi_scale_trans.inverted())
# Saving it to a pdf file.
fig.savefig('ax2_figure.pdf', bbox_inches=extent.expanded(1.1, 1.2))
EDIT: I believe I may have misunderstood what you want. If you want to save EACH plot individually, say as 4 different pages in a pdf, you can do the following adapted from this answer: https://stackoverflow.com/a/29435953/16299117
This will save each subplot from the figure as a different page in a single pdf.
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages
fig,ax=plt.subplots(2,2,figsize=(15,10))
x=np.linspace(-3,3)
ax[0,0].plot(x,x**2) # This is just to make an actual plot.
with PdfPages('foo.pdf') as pdf:
for x in range(ax.shape[0]):
for y in range(ax.shape[1]):
extent = ax[x, y].get_window_extent().transformed(fig.dpi_scale_trans.inverted())
pdf.savefig(bbox_inches=extent.expanded(1.1, 1.2))
Here's a dummy script that makes three plots and saves them to PDF.
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
df = pd.DataFrame({"A":np.random.normal(100),
"B":np.random.chisquare(5, size = 100),
"C":np.random.gamma(5,size = 100)})
for i in df.columns:
plt.hist(df[i])
plt.savefig(i+".pdf", format = "pdf")
plt.close()
I'm using spyder, which uses IPython. When I run this script, three windows pop at me and then go away. It works, but it's a little annoying.
How can I make the figures get saved to pdf without ever being rendered on my screen?
I'm looking for something like R's
pdf("path/to/plot/name.pdf")
commands
dev.off()
inasmuch as nothing gets rendered on the screen, but the pdf gets saved.
Aha. Partially based on the duplicate suggestion (which wasn't exactly a duplicate), this works:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
df = pd.DataFrame({"A":np.random.normal(100),
"B":np.random.chisquare(5, size = 100),
"C":np.random.gamma(5,size = 100)})
import matplotlib
old_backend = matplotlib.get_backend()
matplotlib.use("pdf")
for i in df.columns:
plt.hist(df[i])
plt.savefig(i+".pdf", format = "pdf")
plt.close()
matplotlib.use(old_backend)
Basically, set the backend to something like a pdf device, and then set it back to whatever you're accustomed to.
I am referring you to this StackOverflow answer which cites this article as an answer. In the SO answer they also suggest plt.ioff() but are concerned that it could disable other functionality should you want it.
I am writting a script to plot some data.
I am using python 3.7.1 on windows and have the following code to plot:
import pandas as pd
import matplotlib.pyplot as plt
files=['path']
for i in range(len(files)):
data = pd.read_csv(files[i], sep=';', skiprows=17, header=None,engine='python', decimal=",")
c=files[0].split('\\')
path='\\'.join(c[:-1])
x= data.loc[:,0].values
y= data.loc[:,1].values
c,data=None,None
plt.ioff() #turns off the plotting
plt.plot(x,y)
plt.xlabel('x]')
plt.ylabel('y')
plt.savefig(path+'\\ title123') #saves image
I want to transform the dataframe from pandas into a numpy array dtype float64.
Currently, the code I have transforms the data into an object type. I cannot plot this because the code is taking too long to run.
An example of what I am trying to achieve is:
import numpy as np
import matplotlib.pyplot as plt
x=np.linspace(0,10,1000000)
y=np.sin(x)
plt.plot(x,y)
I will leave a link to the file.
https://drive.google.com/open?id=1kir-cGlk3bZSLmvD_tfnbGUaTYzvcW-3
Can anyone give me a help?
Kind Regards!
I just noticed that it was a problem with ',' and '.'. Sort of a math "language" conflict.
However, the for loop runs extremely slow when more than one file is loaded.
Kind regards to all!
For plotting 100,000 to 500,000 data point in a text file I use the following code.
The problem is:
If I copy and paste the data points in a plotting software, reaching the plot takes just 30 seconds but with the following code it may take 1 hour or more to plot by Python.
import numpy as np
import matplotlib.pyplot as plt
from math import *
cmin=502.8571071527562
c,O=np.genfromtxt('textfile.txt',unpack=True)
for i in range(len(O)):
q=exp(-0.5*(c[i]-cmin))
plt.plot(O[i], q, 'bo')
plt.show()
What is the problem? How could I solve it?
I appreciate your help.
Some general rules:
use numpy, not math
avoid for-loops
Do not create unnecessary artists.
Here you want to create a single artist with all points, instead of 500000 single artists with one point each.
import numpy as np
import matplotlib.pyplot as plt
cmin=502.8571071527562
c,O=np.genfromtxt('textfile.txt',unpack=True)
q=np.exp(-0.5*(c-cmin))
plt.plot(O, q, 'bo')
plt.show()