Scatter plot is not getting published in streamlit - python

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)

Related

Use loop for plotting, but plot only particular images from the plot

I have to use different csv files to create plots out of them in the same figure. My coding environment is google colab (it's like Jupyter notebook in google's cloud). So I decided to create a figure and then loop through the files and do the plots. It looks something like this:
import healpy as hp
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(16,12))
ax = fig.add_subplot(111)
for void_file in ['./filepath1.csv','./filepath2.csv','./filepath3.csv', ...]:
helper_image = hp.gnomview(void_file, .....)
data = func1(helper_image, .....)
plt.plot(len(data), data, ......)
What I want is to only add into the figure the plots created with the line plt.plot(len(data), data, ......), but what happens is that also the helper images from the line helper_image = hp.gnomview(....) sneak into the image and spoil it (healpy is a package for spherical data). The line helper_image = .... is only there to make some necessary calculations, but unfortunately they come along with plots.
How can I suppress the creation of the plots by helper_image = hp.gnomview(....)? Or can I somehow tell the figure or ax to include only plots that I specify? Or are there any easy alternatives that don't require a loop for plotting? Tnx
you can use return_projected_image=True and no_plot=True keyword arguments, see https://healpy.readthedocs.io/en/latest/generated/healpy.visufunc.gnomview.html

Plots in Python saving as blank images?

I've created several plots in Python and am attempting to save them as .png files or pdfs. I'm using the following code to create after the data is input:
plt.xlabel('Sersic Index Number', fontsize=16)
plt.ylabel('Number', fontsize=16)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.title('Voids In VIKING', fontsize=20)
And the plot shows up great. However, whenever I use
plt.savefig('Sersic_Voids.png')
to save, it does so and the file shows up on my computer. For every time and filetype I use, the document is blank, without the plot, axes, or anything.
EDIT1: I'm already using the plt.savefig() format to save, but not having any luck. I don't have any plt.show() functions in, and each Jupiter Notebook has about two plots I'm trying to save, neither of which work. I've tried cutting half of the code into a blank workbook to save the first plot, but still trouble. The beginning is input as:
from astropy.io import fits
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
To save matplotlib plots as a file in the PC. Go below way
import matplotlib
import matplotlib.pyplot as plt
Now to make and see a chart, use the .plot() method with passing values to plot. For example, I'll plot simple points as
plt.plot([0, 1, 2, 3, 4], [0, 20, 40, 60, 85])
To add axis-labels
plt.xlabel('Number of people')
plt.ylabel('Total Weight')
To pop-up the graph call .show() method as,
plt.show()
To save the graph which you just plotted use .savefig() method
plt.savefig('weight_calculation.png')
weight_calculation -> filename
You can also give the path to the directory you want to save
Use dpi to change the resolution of figures you want to save
There few other add ons which you can use like,
transparent, bbox_inches, and pad_inches.
Change bbox_inches to change the size of outer white box around the figure

Ploting and labeling data with variables matplotlib

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)

Python SAC plot w/ grid

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.

How do I write a Latex formula in the legend of a plot using Matplotlib inside a .py file?

I am writing a script in Python (.py file) and I am using Matplotlib to plot an array.
I want to add a legend with a formula to the plot, but I haven't been able to do it.
I have done this before in IPython or the terminal. In this case, writing something like this:
legend(ur'$The_formula$')
worked perfectly. However, this doesn't work when I call my .py script from the terminal/IPython.
The easiest way is to assign the label when you plot the data,
e.g.:
import matplotlib.pyplot as plt
ax = plt.gca() # or any other way to get an axis object
ax.plot(x, y, label=r'$\sin (x)$')
ax.legend()
When writing code for labels it is:
import pylab
# code here
pylab.plot(x,y,'f:', '$sin(x)$')
So perhaps pylab.legend('$latex here$')
Edit:
The u is for unicode strings, try just r'$\latex$'

Categories