Line Graphs in Anaconda - python

I am writing a Python program to generate line graphs of cryptocurrency prices.
The goal is to be able to overlay multiple arbitrary pairs, i.e., BTC/USD + ETH/BTC, or BTC/USD + BCH/LTC + XRP/BTG, across the same horizontal timeline, similar to https://coinmarketcap.com/currencies/ethereum/
The bells and whistles in the above example are not required. It doesn't need click-to-zoom technology, the log-scale button, or fancy tool tips, if these features increase the implementation difficulty. Separate colors for each line would be helpful. This is the format of the data I have to work with:
https://min-api.cryptocompare.com/data/histominute?fsym=BTC&tsym=USD&limit=60&aggregate=1&e=Coinbase
https://min-api.cryptocompare.com/data/histominute?fsym=ETH&tsym=BCH&limit=30&aggregate=1&e=CCCAGG
Currently, I have Anaconda 3.6 on Visual Studio, which according to https://docs.anaconda.com/anaconda/packages/py3.6_win-64.html should include multiple packages to plot this data without needing to manually install third party code through a command line. However, when I try to import any of them (i.e., matplotlib, bokeh, seaborn), I receive a "ModuleNotFoundError" message, so I'm not sure if my Anaconda is functioning properly. What is the easiest way to graph this data with Anaconda?

The python interpreter in VSCode is probably not using your Anaconda installation. In the VSCode python shell, type import sys and then sys.version and it should tell you the version of python you are using.
Here is some code to get you started with doing this in bokeh, a library that comes with Anaconda. Instead of using Visual Studio (or Visual Studio Code--I'm not sure which one you are referring to), I used jupyter notebook, and some of the import here are specific to that environment (to show the bokeh graph inline). You may want to format the date differently.
from bokeh.plotting import figure, output_file, show
from bokeh.io import output_notebook
import numpy as np
output_notebook()
import requests
import datetime
from math import pi
def format_date(utc_time):
time = datetime.datetime.fromtimestamp(int(utc_time))
return time
url1 = "https://min-api.cryptocompare.com/data/histominute?fsym=BTC&tsym=USD&limit=60&aggregate=1&e=Coinbase"
url2 = "https://min-api.cryptocompare.com/data/histominute?fsym=ETH&tsym=BCH&limit=30&aggregate=1&e=CCCAGG"
r1 = requests.get(url1)
r2 = requests.get(url2)
r1_source = r1.json()["Data"]
r2_source = r2.json()["Data"]
r1_data = [i["close"] for i in r1_source]
r1_time = [format_date(i["time"]) for i in r1_source]
# r2_data = [i["close"] for i in r2_source]
# r2_time = [i["time"] for i in r2_source]
p = figure(plot_width=800, plot_height=400)
p.line(r1_time,r1_data, line_width=2)
# p.line(r2_time, r2_data, line_width=2, line_color="red")
p.xaxis.major_label_orientation = pi/4

Related

Plot points in google map with python with google api

I'm trying to plot some points on a map, and when searching on the internet, I found [this][1] tutorial with Google Maps and Bokeh library. The problem is that, after doing all the steps to get a key in google api, to set the environment variable, when I try to plot, it says that google maps weren't able to load.
Since I don't have much time, and I really need to plot some data (UTM coordinates, that I Intend to transform to latitude and longitude with pyproj), I was wondering if someone knows, another library, with examples, easy to work, with where I could plot my data (is a pandas dataframe with East, Northing, Elevation).
This is the code from the example I'm trying to reproduce:
import os
ACCESS_KEY_ID = os.environ.get('ACCESS_KEY_ID')
api_key = os.environ['SECRET_ACCESS_KEY']
import pandas as pd
from bokeh.io import output_notebook
df = pd.read_csv('dvf_gex.csv')
lat, lon = 46.2437, 6.0251
from bokeh.io import show
from bokeh.plotting import gmap
from bokeh.models import GMapOptions
bokeh_width=500
bokeh_height=500
def plot(lat, lng, zoom=10, map_type='roadmap'):
gmap_options = GMapOptions(lat=lat, lng=lng,
map_type=map_type, zoom=zoom)
p = gmap(api_key, gmap_options, title='Pays de Gex',
width=bokeh_width, height=bokeh_height)
show(p)
return p
this is the error I got:
[![enter image description here][2]][2]
The error I get on my browser console is:
[![enter image description here][3]][3]
I have activated the Maps Embed API, is that enough? should I have another API activated?
[1]: https://thedatafrog.com/en/articles/show-data-google-map-python/#commento-login-box-container
[2]: https://i.stack.imgur.com/SxoXS.png
[3]: https://i.stack.imgur.com/rjqc2.png
I guess Google has retired the GMap version that Bokeh 2.4.2 specifies by default? That is pretty annoying and user-unfriendly of them. However, you can specify any API version to use by passing it to gmap, e.g.
gmap(api_key, api_version="3.47", ...)

.plot() command does not display anything

I have this code based on this question, just a different point Extract constrained polygon using OSMnx
I am trying to plot the block in which the point is located but it does nothing, it just prints "Done" but I cannot see any image
import osmnx as ox
import geopandas as gpd
import shapely
point = (50.090464, 14.400070)
streets_graph = ox.graph_from_point(point, distance=500, network_type='drive')
streets_graph = ox.project_graph(streets_graph)
streets = ox.save_load.graph_to_gdfs(streets_graph, nodes=False, edges=True,
node_geometry=False, fill_edge_geometry=True)
point = streets.unary_union.centroid
polygons = shapely.ops.polygonize(streets.geometry)
polygons = gpd.GeoSeries(polygons)
target = polygons.loc[polygons.contains(point)]
target_streets = streets.loc[streets.intersection(target.iloc[0]).type == 'MultiLineString']
ax = target_streets.plot()
gpd.GeoSeries([point]).plot(ax=ax, color='r')
print("Done")
I do not think this may help but I am using Visual Studio Code
Thank you very much
Since my comment answered your question, I will summarize it here for other people:
When using plotting library dependent on matplotlib, like geopandas or seaborn, you will need to import matplotlib in order to show the plot. The way matplotlib is imported will depend on whether you are using Jupyter or simple scripting (.py) files.
For Jupyter you need to import it like this:
%matplotlib inline
For simple scripting (.py) file you need to import it like this:
import matplotlib.pyplot as plt
Then when you want to show your plot you simply do
plt.show()
Hope it helps!

Printing image in r-markdown using matplotlib and python code

I am trying to run the python code using the R-Markdown file (RMarkdown to pdf).
What I achieved till now -
1- I am able to configure my python engine using knitr and reticulate library
2- I am able to execute my python codes.
What I tried -
1- I tried all the methods which are discussed in this forum, but nothing is working out.
2- I also tried to save the image,(as one of the posts here suggests), but that also is not working.
My problem -
1- When I am trying to plot a graph using matlplotlib and command plt.imshow() and plt.show(), it's not printing the image in the output. Rather it's showing the image in a separate window. You can see my results in the attached image.
Result_of_my_code
Here is my code
```{r setup, include=FALSE}
library(knitr)
library(reticulate)
knitr::knit_engines$set(python = reticulate::eng_python)
```
```{python}
import numpy as np
import os
import torch
import torchvision.datasets as dsets
import matplotlib.pyplot as plt
print(os.getcwd())
os.chdir('D:\\1st year\\Python codes\\CIFR Analysis\\self contained analysis')
print(os.getcwd())
train_mnist = dsets.MNIST("../data", train=True)
test_mnist = dsets.MNIST("../data", train= False)
print(len(train_mnist))
#print(train_mnist[0][0])
plt.imshow(train_mnist[0][0], cmap="gray")
#plt.savefig("trainzero.png")
plt.show()
```
Kindly, help me to fix this issue, as I want to compile my python codes using the R markdown file.
thanks
So with R Markdown, you have to do some things a little differently. In the following, I have a dataframe with two series created by concatenating them. The original plotting code in the Jupyter Notebook is as follows and just printed out the series.
# make a plot of model fit
train.plot(figsize=(16,8), legend=True)
backtest.plot(legend=True);
However, it does not work with way with R Markdown. Then with plotting, you always have to assign them, and with the code below, you get the same plot.
dfreg = pd.concat([reg, backtest], axis = 1)
ax = dfreg.plot(figsize=(16,8), legend = True)
ax1 = predictions.plot(legend=True)
plt.show()
This is common with other plotting functions like plot_acf() too.

Plotting a large number of stacked spheres generated from python-- mayavi? paraview and pyevtk? How to transmute .npy to .vtk?

I want to produce plots like this, except with many more particles. Matplotlib is woefully inadequate.
Right now I am using mayavi in python 3.5 running through a jupyter notebook. As I need to plot 5x10^5 spheres it will not be practical, since time is a limiting factor already at 2x10^4 spheres.
Here is my python code to produce the mayavi plot. I have a numpy array of values [a,r,x,y,z]. It's not relevant what the first quantity is for this problem.
"""VISUALIZATION WITH MAYAVI"""
#I think this is too slow to be practical.
#view particles with mayavi
import mayavi
from mayavi import mlab
%gui qt
def plot_sphere(p): #feed it p and get back a sphere \n",
t1,R,a,b,c = p
[phi,theta] = np.mgrid[0:2*np.pi:12j,0:np.pi:12j] #increase the numbers before j for better resolution but more time
x = R*np.cos(phi)*np.sin(theta) + a
y = R*np.sin(phi)*np.sin(theta) + b
z = R*np.cos(theta) + c
return mlab.mesh(x, y, z)
#run s over all particles and plot it
def view(particles):
for p in particles:
plot_sphere(p)
view(spheres)
This code produces plots like this:
I have been told I should look into writing my numpy arrays to .vtk files using evtk, then visualizing these in paraview. I downloaded paraview and read this, but perhaps my version of python is limiting me? First, install pyevtk-- okay:
I tried conda install -c opengeostat pyevtk=1.0.0, but it fails due to incompatibility with my python version. I looked for details but could not find any.
Next I downloaded the repository [here][https://pypi.python.org/pypi/PyEVTK/1.0.0], then used pip to install it successfully.
Next I put evtk.py, vtk.py, hl.py, and xml.py, and tried some examples in the repository-- none of them work. Seemingly there is some problem with
from .vtk import *
type commands. I tried replacing all of these in the four .py files with
from evtk import vtk
from vtk import *
and such, but no luck. Long story short, I can't get pyevtk working to export my numpy arrays as .vtk files. I could use some help in this regard, or better yet I would love a different option to get my numpy arrays rendered by paraview. Any help is appreciated !
Ok, I solved my own problem. This image is made using paraview, after converting numpy arrays to a .vtu object using pyevtk.
Out of the box, the repository did not work, there was some problem with importing the modules inside the four .py files, so I modified them all. Instead of from .vtk import *, I changed it to from vtk import *, and so on, in every module in the library. evtk.py was not able to import a class from xml.py, so I just copied it and pasted, then deleted xml.py. After some tinkering and clueless modifying to make the errors go away, eventually it worked.

How do I import a plotly graph within a python script?

Is there any API call to import a plotly graph as a .png file within an existing python script? If so, what is it?
For example, having just created a graph using the plotly module for python...
py.plot([data0, data1], layout = layout, filename='foo', fileopt='overwrite')
...is there a way of retrieving that graph as a .png within the same python script?
Yes, there is.
First, update to the latest version of the plotly python package with
$ pip install plotly --upgrade
Then, something like
>>> import plotly.plotly as py
>>> py.sign_in('your-username','your-api-key')
>>> data = [{'x':[1,2,3], 'y':[1,4,9]}]
>>> url = py.plot(data, filename='some-data') # gen. online plot
>>> py.image.save_as(data, 'some-data.png') # gen. png plot
For more:
https://plot.ly/python/static-image-export/
https://plot.ly/python/get-requests/
Another solution: add .png to any public plotly graph, e.g.
import requests
r = requests.get('https://plot.ly/~chris/1638.png')
This works for any public plotly graph. .png, .svg, .pdf are supported.
.py, .jl, .json, .m, .r, .js can be used to view the code could regenerate the graph (more here: http://blog.plot.ly/post/89402845747/a-graph-is-a-graph-is-a-graph)

Categories