For the moment this code always opens the following candlestick chart on a google chrome page, however, I wanted to appear on a Tkinter.
I tried to use candlestick_ohlc for Tkinter (it works best on apparently Tkinter) but it does not give me the same appearance as this candlestick.
Is there any way that I can make this candlestick chart ( using go.candlestick) appear on Tkinter?
import yfinance as yf
import plotly.graph_objs as go
from plotly.subplots import make_subplots
import matplotlib.pyplot as plt
data = yf.download(tickers='BTC-USD', period='1mo', interval='5m')
print(data.tail())
fig3 = make_subplots(specs=[[{"secondary_y": True}]])
fig3.add_trace(go.Candlestick(x=data.index,
open=data['Open'],
high=data['High'],
low=data['Low'],
close=data['Close'],
))
fig3.update_yaxes(range=[0,700000000],secondary_y=True)
fig3.update_yaxes(visible=False, secondary_y=True)
fig3.update_layout(xaxis_rangeslider_visible=False)
fig3.update_layout(title={'text':'BTC-USD', 'x':0.5},yaxis_title='Price',xaxis_title='Date-Time')
fig3.show()
Related
I have a df - Wards - that contains the number of different events that happen on each ward of a hospital. I just want a simple bar chart of the totals of these events. I have used plotly before - I am no means an expert (evidently!) but I can't figure out where I am going wrong! With the code below I am seeing anything with fig.show(). I added the fig.write_image command to test - this returns the correct graph - but I can't figure out why my fig.show() command doesn't work
import plotly.express as px
import matplotlib.pyplot as plt
fig = px.bar(Wards, x='Ward', y='Total_Tasks')
fig.write_image("fig1.png")
fig.show()
I tried to duplicate your code but of course I don't have the data, so I made some up and I also didn't know for sure what modules you are importing, so I used the help at:
https://plotly.com/python/getting-started/
but anyway, here is what I came up with
that seems to work.
import plotly.express as px
import matplotlib.pyplot as plt
fig = px.bar(x=["a", "b", "c"], y=[1, 3, 2])
plt.savefig('fig1.png',bbox_inches="tight",dpi=600)
fig.show()
I am using Spyder ide. I have plotly 5.5.0 installed on my pc. The following executes with no errors but does not show/popup the 3d interactive plot.
Code:
import plotly.express as px
df = px.data.iris()
fig = px.scatter_3d(df, x='sepal_length', y='sepal_width', z='petal_width',
color='species')
fig.show()
To be able to interact with the figure running from Spyder you will need to call show with the 'browser' renderer (this will show the figure on your default browser). The code provided with this change will look something like this:
import plotly.express as px
df = px.data.iris()
fig = px.scatter_3d(df, x='sepal_length', y='sepal_width', z='petal_width',
color='species')
fig.show(renderer='browser')
I am using the waterfall_chart package in Python to create a waterfall figure. The package mainly uses matplotlib in the backend, so I was trying to use the tls.mpl_to_plotly(mpl_fig) function to covert the matplotlib figure into plotly. But when converting, an error pops up. Is there a way to convert waterfall_chart into plotly or is there an easy way to create the chart directly in plotly? I saw some previous discussion on similar chart in plotly, but it involved pretty manual coding of the chart number.
You could use the following code to recreate the chart.
import waterfall_chart
import matplotlib.pyplot as plt
import plotly.tools as tls
a = ['sales','returns','credit fees','rebates','late charges','shipping']
b = [10,-30,-7.5,-25,95,-7]
mpl_fig = plt.figure()
waterfall_chart.plot(a, b)
plt.show()
waterfall chart
But when I try to convert to plotly using mpl_to_plotly(), there is an error:
plotly_fig = tls.mpl_to_plotly(mpl_fig)
ValueError: min() arg is an empty sequence
The detail of the waterfall_chart package could be found here: https://github.com/chrispaulca/waterfall/blob/master/waterfall_chart.py
My answer addresses
[...] or is there an easy way to create the chart directly in plotly?
With newer versions of plotly you can use plotly.graph_objs.Waterfall.
Below is a basic example with your data sample with a setup that uses iplot in an off-line Jupyter Notebook:
Plot:
Code:
# imports
import plotly
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
from IPython.core.display import display, HTML
import plotly.figure_factory as ff
import plotly.graph_objs as go
import pandas as pd
import numpy as np
# setup
display(HTML("<style>.container { width:35% !important; } .widget-select > select {background-color: gainsboro;}</style>"))
init_notebook_mode(connected=True)
np.random.seed(1)
import plotly.offline as py
import plotly.graph_objs as go
py.init_notebook_mode(connected = False)
# your values
a = ['sales','returns','credit fees','rebates','late charges','shipping']
b = [10,-30,-7.5,-25,95,-7]
# waterfall trace
trace = go.Waterfall(
x = a,
textposition = "outside",
text = [str(elem) for elem in b],
y = b,
connector = {"line":{"color":"rgb(63, 63, 63)"}},
)
layout = go.Layout(
title = "Waterfall chart, plotly version 3.9.0",
showlegend = True
)
iplot(go.Figure([trace], layout))
Check your version with:
import plotly
plotly.__version__
Update your version in a cmd console using:
pip install plotly --upgrade
List a has a length of 6, list b has a length of 5.
Matplotlib refuses to display an empty array, list or whatever.
Solve it to add a number or 0 to b or add an if to your code, to avoid matplotlib gets an empty sequence.
I get an 'PlotlyRequestError: No message' when I execute the code.
import plotly
import plotly.plotly as py
import plotly.graph_objs as go
Filedata = pd.read_csv('C:\\Documents\\Book4.csv')
data = [go.Scatter(x=Filedata.ix[:,0],y=Filedata.ix[:,1])]
layout = go.Layout(
title='Analysis 2016',
xaxis=dict(title='Startdate'),
yaxis=dict(title='Conductivity'))
fig = go.Figure(data=data, layout=layout)
py.iplot(fig)
This is because you are trying to plot online which requires credentials based authentication. To plot offline, use plotly.offline's plot class to accomplish this without authentication.
from plotly.offline import plot
and then use this plot to plot your figure.
I had the same issue and I solved the problem by importing plotly like this:
import plotly.plotly as py
import plotly.graph_objs as go
# these two lines allow your code to show up in a notebook
from plotly.offline import init_notebook_mode, iplot
init_notebook_mode()
And then calling iplot like this:
plotly.offline.iplot(...)
I had the same issue and I solved the problem by importing plotly and cufflinks like this:
from plotly.offline import iplot
import cufflinks as cf
and then apply
cf.go_offline()
I've been using matplotlib for five months now on a daily basis, and I still find creation of new figures confusing.
Usually I create a figure with 2x2 subplots using, for example, somthing like:
import matplotlib.pyplot as plt
import itertools as it
fig,axes = plt.subplots(2,2)
axit = (ax for ax in it.chain(*axes))
for each of four data series I want to plot:
ax = next(axit)
ax.plot(...)
The question I have now is: how can operate completely independently of pyplot, ie, how can I create a figure, populate it with plots, make style changes, and only tell that figure to appear at the exact moment I want it to appear. Here is what I am having trouble with:
import matplotlib as mpl
gs = gridspec.GridSpec(2,2)
fig = mpl.figure.Figure()
ax1 = fig.add_subplot(gs[0])
ax1.plot([1,2,3])
ax2 = fig.add_subplot(gs[1])
ax2.plot([3,2,1])
After running the above, the only thing that comes to mind would be to use:
plt.draw()
But this does not work. What is missing to make the figure with the plots appear? Also, is
fig = mpl.figure.Figure()
all I have to do to create the figure without pyplot?
This works for me without matplotlib.pyplot
import sys
from PyQt5 import QtWidgets
from matplotlib.backends.backend_qt5agg import (
FigureCanvasQTAgg as FigureCanvas)
from matplotlib.figure import Figure
import numpy as np
fig=Figure()
canvas=FigureCanvas(fig)
ax=canvas.figure.add_subplot(111)
x=np.arange(-5,5,0.1)
y=np.sin(x)
ax.plot(x,y)
canvas.show()
app=QtWidgets.QApplication(sys.argv)
app.exec()
You could attach a suitable backend to your figure manually and then show it:
from matplotlib.backends import backend_qt4agg # e.g.
backend_qt4agg.new_figure_manager_given_figure(1, fig)
fig.show()
... but why not use pyplot?