I've been collecting data from experiments and dumping them into .txt files and I decided to try and write a quick script to plot them with matplotlib. The plotting works fine, but I do not know how to label the plot based on the file name.
from numpy import *
from pylab import *
from matplotlib import rc
import sys
import os
rc('text',usetex=True)
rc('font',**{'family':'serif','serif':['Computer Modern']})
os.chdir(".")
for files in os.listdir("."):
if files.endswith(".txt"):
f = open(files,'r')
temp = []
for l in f:
temp.append(float(l))
plot(temp,labels=files)
hold(True)
legend(loc='lower left')
hold(False)
# Save the figure in a separate file
savefig('test.png')
# Draw the plot to the screen
show()
The problem seems to be with plot(temp,lables=files). If I put lables=files I get the error TypeError: There is no line property "labels". If I try and put labels='files', all the plots are labelled files which is useless. Does anyone know how to assign a lable to a plot based on a variable?
You want to use label, not lables or labels.
plot(temp,label = files)
Related
This below code for streamlit Python program is working fine.
avg=s/c
k=s2.std(axis=1)
cv=(k/avg)
b6=b9.assign(average_value=avg,Std_Dev=k,Coff_Var=cv)
b8=b6.loc[b6['average_value'] > 1]
st.write(b8)
However , I wanted to plot a scatter plot chart of the variables and wrote the following lines
graph=pd.DataFrame(b6,columns=['Std_Dev','Coff_Var']) <------------This is line 61
plt.scatter(graph['Std_Dev'],graph['Coff_Var'])
st.pyplot()
I am not getting the results and its resulting in following error.
TypeError: Expected tuple, got str
File "C:\Users\bahlrajesh23\datascience\data_charts.py", line 61, in
graph=pd.DataFrame(b6,columns=['Std_Dev','Coff_Var'])
So I'm not sure what your variable b6 is, but it seems to be a string type and holds this path to a file: "C:\Users\bahlrajesh23\datascience\data_charts.py", not a tuple of data points.
If you're trying to create a pandas data frame from a file you need to pass in data or use pd.read_ and then the file type usually (csv is pd.read_csv, excel is pd.read_excel, etc... ). Then you can pass this a path to the file you want to use:
data = pd.read_csv("path/to/file/data.csv")
Not sure what plotting package your using? plt could refer to matplotlib, altair, etc.. but I would generally recommend making a figure and axes handles that you can use to write to the screen (this is a matplotlib example):
import matplotlib.pyplot as plt
import streamlit as st
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
plt.scatter(data)
st.write(fig)
I have hundreds of thousands of images which I have to get from URL, see them ,tag them and then save them in their respective category as spam or non spam. On top of that, I'll be working with google which makes it impossible. My idea is that instead of looking at each image by opening, analysing, renaming and then saving them in directory, I just get the image from url, see within a loop, input a single word and based on that input, my function will save them in their respective directories.
I tried doing
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import Image
fg = plt.figure()
for i in range(5):
plt.imshow(np.random.rand(50,50))
plt.show()
x = input()
print(x)
but instead of overwriting the existing frame, it is plotting a different figure. I have even used 1,1 subplot inside a loop but it is not working. Ipython's method does not even display inside a loop either. Could somebody please help me with this problem.
You can make use of matplotlib's interactive mode by invoking plt.ion(). An example:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib notebook
fig, ax = plt.subplots()
plt.ion()
plt.show()
for i in range(5):
ax.imshow(np.random.rand(50,50)) # plot the figure
plt.gcf().canvas.draw()
yorn = input("Press 1 to continue, 0 to break")
if yorn==0:
break
Expected output:
I've tried to plot images of my loaded 2D data (512x512 pixels) in a loop by matplotlib with Python3. But it turns out to show weird images with multiple colorbars. Here is my code:
import numpy as np
import sys
import os
from load_images import load, File
import matplotlib.pyplot as plt
from matplotlib import cm
arr_spe = [x for x in os.listdir() if x.endswith(".SPE")]
for x in arr_spe:
try:
dat = load(x)
plt.imshow(dat,cmap=cm.jet, vmax = 2000)
plt.colorbar()
plt.savefig(x[:-4]+'.png', dpi=500, bbox_inches='tight')
except ValueError as error:
print('ValueError(empty)-'+x)
I use the code to load my data in the following link: Reading SPE file from CCD camera by naming the code as load_images.py.
And I got many images like
Does anybody have ideas to solve this issue? Just simply show single colorbar in an image
I am building a GUI that is a heads-up display and in the background an animation is played.
The tool is supposed to read data from a text file that contains the information that will be displayed. Also, the animation is a library of images. Thus, each second the code looks at a line in the table and displays the information for that row as well as the image associated with that row.
I have implemented a possible solution to this particular need using Matplotlib. My issue is that once the code is ran, if I click anywhere on the screen, or try to open a new window while the loop is running, I get a "(Not Responding") status on the program toolbar
Figure 1 - Not Responding
How can I prevent this issue from happening?
Or are there better ways to implement this functionality? I has to be able to read a txt/csv file as well as render the images one after the other.
Here is a sample of the code:
import matplotlib.pyplot as plt
import numpy as np
import time
from scipy.misc import imread
import matplotlib.cbook as cbook
import pandas as pd
from pylab import *
#Open file with information for HUD
filename = "data.txt"
rndz_data = pd.read_table(filename, sep="\s+")
frames = np.arange(5)
plt.ion()
fig = plt.figure()
#Create array of image files
datafile = [cbook.get_sample_data('rndz0000.png'),
cbook.get_sample_data('rndz0001.png'),
cbook.get_sample_data('rndz0002.png'),
cbook.get_sample_data('rndz0003.png'),
cbook.get_sample_data('rndz0004.png')]
#Create plot and animate
for i in frames:
img = imread(datafile[i])
plt.clf()
plt.imshow(img, zorder=0, extent=[0.5, 8.0, 1.0, 7.0])
plt.plot
plt.draw()
time.sleep(1)
I'm required to use the information from a .sac file and plot it against a grid. I know that using various ObsPy functions one is able to plot the Seismograms using st.plot() but I can't seem to get it against a grid. I've also tried following the example given here "How do I draw a grid onto a plot in Python?" but have trouble when trying to configure my x axis to use UTCDatetime. I'm new to python and programming of this sort so any advice / help would be greatly appreciated.
Various resources used:
"http://docs.obspy.org/tutorial/code_snippets/reading_seismograms.html"
"http://docs.obspy.org/packages/autogen/obspy.core.stream.Stream.plot.html#obspy.core.stream.Stream.plot"
The Stream's plot() method actually automatically generates a grid, e.g. if you take the default example and plot it via:
from obspy.core import read
st = read() # without filename an example file is loaded
tr = st[0] # we will use only the first channel
tr.plot()
You may want to play with the number_of_ticks, tick_format and tick_rotationparameters as pointed out in http://docs.obspy.org/packages/autogen/obspy.core.stream.Stream.plot.html.
However if you want more control you can pass a matplotlib figure as input parameter to the plot() method:
from obspy.core import read
import matplotlib.pyplot as plt
fig = plt.figure()
st = read('/path/to/file.sac')
st.plot(fig=fig)
# at this point do whatever you want with your figure, e.g.
fig.gca().set_axis_off()
# finally display your figure
fig.show()
Hope it helps.