AttributeError: module 'chart_studio.plotly' has no attribute 'offline' - python

I am quite struggling with plotly offline mode in jupyter notebook. I used to use import plotly.plotly as py and then use py.offline.plot(). Now it tells me plotly.plotly is depreciated and want me to use chart_studio.plotly. Now I don't know how to use offline mode for chart_studio.plot. I either got an error of Authentication is required or chart_studio doesn't have offline mode. I just want to plot some figures in jupyter notebook using plotly. How can I fix the issue? Thanks
import chart_studio.plotly as py
from chart_studio.grid_objs import Grid, Column
import plotly.figure_factory as FF
import pandas as pd
import time
import pickle
filename_pickle='dataset.pkl'
try:
dataset=pd.read_pickle(filename_pickle)
except FileNotFoundError:
url = 'https://raw.githubusercontent.com/plotly/datasets/master/gapminderDataFiveYear.csv'
dataset = pd.read_csv(url)
dataset.to_pickle(filename_pickle)
table = FF.create_table(dataset.head(10))
#py.iplot(table, filename='animations-gapminder-data-preview')
py.offline.iplot(table)
Previously: I use plotly.plotly
import plotly.plotly as py
from plotly.grid_objs import Grid, Column
from plotly.tools import FigureFactory as FF
# chart_studio is for online mode only
# import chart_studio.plotly as py
# from chart_studio.grid_objs import Grid, Column
# import plotly.figure_factory as FF
import pandas as pd
import time
import pickle
filename_pickle='dataset.pkl'
try:
dataset=pd.read_pickle(filename_pickle)
except FileNotFoundError:
url = 'https://raw.githubusercontent.com/plotly/datasets/master/gapminderDataFiveYear.csv'
dataset = pd.read_csv(url)
dataset.to_pickle(filename_pickle)
table = FF.create_table(dataset.head(10))
#py.iplot(table, filename='animations-gapminder-data-preview')
py.offline.iplot(table)
then I got an error of
ImportError:
The plotly.plotly module is deprecated,
please install the chart-studio package and use the
chart_studio.plotly module instead.

You just have to import plotly not plotly.plotly and call the offline.iplot with your chart at the parameter as shown in my example:
import plotly
import plotly.graph_objs as go
data = [go.Scatter(x=[1,2,3,4], y=[1,2,4,3])]
plotly.offline.iplot(data)

Related

How to resolve PyDrive authentication permanantly

I had one more problem with my app on stremalit. I am using PyDrive library to connect with google drive where I am uploading photos for educational purposes. The problem is that every week the app is throwing authentication error. The app is on the streamlit cloud. In my github directory I have clients_secrets.json file, creds.json file and also settings.yaml file.
Here is my code:
import streamlit as st
import pandas as pd
import requests
import sqlalchemy as db
#import matplotlib.pyplot as plt
import leafmap.foliumap as leafmap
from sqlalchemy import create_engine
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy import text
from plotly import graph_objects as go
from plotly.subplots import make_subplots
import branca
#import os
from pathlib import Path
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
import streamlit as st
#import logging
import numpy as np
from PIL import Image
#logging.getLogger('googleapicliet.discovery_cache').setLevel(logging.ERROR)
gauth = GoogleAuth()
gauth.CommandLineAuth()
drive = GoogleDrive(gauth)
What I am doing at the moment is changing creds.json file the moment my credentials are expired. But I wish that I won't need to do it all the time. Any idea how can I make authentication process automatic without the need to change the creds.json file every week?
I tried to change creds.json file every week

Error opening '*.wav': File contains data in an unknown format

I'm trying to run the following code:
import os
import librosa
import IPython.display as ipd
import matplotlib.pyplot as plt
import numpy as np
from scipy.io import wavfile
import warnings
warnings.filterwarnings("ignore")
train_audio_path = 'train/audio/'
samples, sample_rate = librosa.load(train_audio_path+'yes/0a7c2a8d_nohash_0.wav', sr = 16000)
But get two errors:
Error opening 'train/audio/yes/0a7c2a8d_nohash_0.wav': File contains data in an unknown format
and
NoBackendError:
I've tried downloading ffmpeg and gstreamer to fix the second error but no luck. I'm not sure what to do about the first error as I have imported libraries that should be able to handle .wav files.
Thank you for your help in advance.

What is the json file I need to read?

enter image description hereI need to download satellite images using python. I have found a code in GitHub but I did not understand what at this line. Please help me what it exactly is.
Visit https://github.com/kscottz/PythonFromSpace/blob/master/TheBasics.ipynb
import sys
import os
import json
import scipy
import urllib
import datetime
import urllib3
import rasterio
import subprocess
import numpy as np
import pandas as pd
import seaborn as sns
from osgeo import gdal
from planet import api
from planet.api import filters
from traitlets import link
import rasterio.tools.mask as rio_mask
from shapely.geometry import mapping, shape
from IPython.display import display, Image, HTML
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
urllib3.disable_warnings()
from ipyleaflet import (
Map,
Marker,
TileLayer, ImageOverlay,
Polyline, Polygon, Rectangle, Circle, CircleMarker,
GeoJSON,
DrawControl
)
%matplotlib inline
# will pick up api_key via environment variable PL_API_KEY
# but can be specified using `api_key` named argument
api_keys = json.load(open("apikeys.json",'r'))
client = api.ClientV1(api_key=api_keys["PLANET_API_KEY"])
# Make a slippy map to get GeoJSON
api_keys = json.load(open("apikeys.json",'r'))
client = api.ClientV1(api_key=api_keys["PLANET_API_KEY"])
What is the meaning of these two lines. What file should I upload for apikeys.json
You should follow this link to get an API Key.
https://support.planet.com/hc/en-us/articles/212318178-What-is-my-API-key-
apikeys.json is a JSON file of following format/content in json:
{"PLANET_API_KEY":"<Some API Key here>"}
json.load(...) API loads this json file as a dictionary

python offline plotly saves the file always in default file name how to save in differrent name

I have the following code to graph using plotly offline .
import plotly
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
import plotly.graph_objs as go
init_notebook_mode(connected=True)
#import plotly.plotly as py
......
......
......
fig = dict(data=data, layout=layout)
iplot(fig, filename = 'result.html')
plot(fig,show_link = True)
This stores the html output in a local drive where the python files is available but it always stores with the default file name called temp-plot.html
This overwrites the file all time . How to save the file in desired name in html format using offline plotly
what is the change in the code that would resolve this issue.
You should use the same args for plot:
plot(fig,show_link = True, filename = 'result.html')

Can not save file using the below python code. Error: numpy.ndarray object has no attribute 'save'

import os
import sys
import numpy as np
import scipy
import pylab
import pymorph
import mahotas
import matplotlib.pyplot as plt
import Image
from scipy import ndimage
from pymorph import regmax
from PIL import Image
path='all_images'
for file in os.listdir(path):
current = os.path.join(path, file)
extension = os.path.splitext(current)[-1]
fileType = extension.upper()
print(current)
if os.path.isfile(current):
img = mahotas.imread(current)
imgf = ndimage.gaussian_filter(img, 8)
pylab.gray()
imgf.save('dnaa.gif')
Can not save file using the below python code. Error: numpy.ndarray object has no attribute 'save'. Can anyone help how to save file using pylab. I guss the last line of the code has some issue.
Use mahotas.imsave('dnaa.gif', imgf) instead. The NumPy array you get from gaussian_filter doesn't have save functionality built in.

Categories