I'm have some trouble with the DatetimeTickFormatter object from Bokeh. Plots randomly won't generate/update.
I have been searching and found this post at Bokeh, where it states that Plot not shown if DatetimeTickFormatter partially defined. I need some help with how to define it properly. Currently I'm doing this:
from bokeh.models.formatters import DatetimeTickFormatter
from bokeh.plotting import figure
DTF = DatetimeTickFormatter()
DTF.hours = ["%H:%M"]
DTF.days = ["%d/%m/%Y"]
DTF.months = ["%d/%m/%Y"]
DTF.years = ["%d/%m/%Y"]
and
p = figure()
p.xaxis.formatter = DTF
How should I define DTF “properly”?
Related
Hi community maybe you can help me. The last couple of days I was trying to find a solution to plot an image in Django with plotly because I need a 2nd trace with a scatter on top of it and additional a slider wo move around. But first things first. In order to plot an image from an URL I've put in the following in views.py in my Django app
views.py
from skimage import io
def slide_plot(centroid=1):
#steps = Ypixels.objects.filter(centroid__in=[centroid]).order_by('step').values_list('step', falt=True).distinct()
#CentroidCount.objects.filter(centroid__in=[centroid]).order_by('id_observation').values_list('id_observation', flat=True).distinct()
url = 'https://www.cs.technik.fhnw.ch/iris/sji_png/images/20140910_112825_3860259453/20140910_112825_3860259453_1400_1176.jpg'
img_array = io.imread(url)
image = go.Image(
source=url
)
layout = go.Layout(
title='Appearances for Centroids',
xaxis=dict(
title='Step',
),
paper_bgcolor='rgba(0,0,0,0)',
plot_bgcolor='rgba(0,0,0,0)',
yaxis={
'title':'occurences'
},
)
data = [image]
fig = go.Figure(data=data, layout=layout)
plot_test = plot(fig, include_plotlyjs=False, output_type='div')
return plot_test
once this is resolved I can move to the next step creating the scatter trace.
Any help would be appreciated
I'am trying to display all sharepoint's list name but i'am getting this error :
No handlers could be found for logger "office365.runtime.auth.saml_token_provider.SamlTokenProvider._process_service_token_response"
This is my code :
from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext
url = 'https://abc.sharepoint.com/sites/siteName/'
ctx_auth = AuthenticationContext(url)
if ctx_auth.acquire_token_for_user(username='username#abc.com'
,password ='password'):
ctx = ClientContext(url, ctx_auth)
lists = ctx.web.lists
ctx.load(lists)
ctx.execute_query()
for l in lists:
print(l.properties["Title"])
Thanks
I tested below code here with python 2.7 and it works well.
from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext
tenant_url= "https://company.sharepoint.com"
site_url="https://company.sharepoint.com/sites/sname"
ctx_auth = AuthenticationContext(tenant_url)
if ctx_auth.acquire_token_for_user("abc#company.onmicrosoft.com","mypassword"):
ctx = ClientContext(site_url, ctx_auth)
lists = ctx.web.lists
ctx.load(lists)
ctx.execute_query()
for l in lists:
print(l.properties["Title"])
else:
print(ctx_auth.get_last_error())
Result:
If this is related to ADFS, please refer to this closed question:
https://github.com/vgrem/Office365-REST-Python-Client/issues/85
BR
Well i found a solution to get data for specific sharepoint List
from shareplum import Site
from shareplum import Office365
import json
import csv
import pandas
authcookie = Office365('https://abc.sharepoint.com/', username='username', password='password').GetCookies()
site = Site('https://abc.sharepoint.com/sites/SitesName/', authcookie=authcookie)
sp_list = site.List('ListName')
#print(sp_list)
data = sp_list.GetListItems(fields=['FieldName1','FieldName2'])
c = pandas.read_json(json.dumps(data)).to_csv("output.csv")
So I am currently working on a basic stock program, and I have been able to get my graphs (of stock data from the last month) on my tkinter window any tips on how to actively update my tkinter window would be great! (FYI I am very new to programming, this is my first year, so please try to explain in basic terms!) Heres my code:
import numpy as np
import datetime as dt
import yahoo_finance as yf
import matplotlib.pyplot as plt
from Tkinter import *
import quandl
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
root=Tk()
root.geometry('1400x875')
root.title("Stock Information")
fmain=Frame(root, width=1400, height=900, bg='orange',bd=5)
fmain.place(x=100, y=0)
today=dt.date.today()
thirty_day_graph_frame=Frame(fmain, width=645, height=400,bg='green4',bd=5)
thirty_day_graph_frame.place(x=0, y=444)
thirty_days=dt.timedelta(days=43)
thirty_days_ago=today-thirty_days
five_yrs_graph_frame=Frame(fmain, width=645, height=400, bg='yellow2',bd=5)
five_yrs_graph_frame.place(x=655, y=444)
five_years=dt.timedelta(days=1825)
five_years_ago=today-five_years
def stock_info(stock_name):
stock=yf.Share(stock_name)
stock_price=stock.get_price()
name_price_label=Label(fmain, text=(stock_name,':', stock_price),font=("Times New Roman",23))
name_price_label.place(x=400, y=10)
day_high=quandl.get("WIKI/"+str(stock_name)+".2",start_date=str(today),end_date=str(today))
high_price_label=Label(fmain, text=(str(day_high)), font=("Times New Roman",20))
high_price_label.place(x=400, y=100)
thirty_day_data = quandl.get("WIKI/"+str(stock_name), start_date=str(thirty_days_ago), end_date=str(today),column_index=4) #So quandl.get gives a lot of info, so the column_index=4 is just getting closing prices
five_year_data = quandl.get("WIKI/"+str(stock_name),start_date=str(five_years_ago), end_date=str(today), column_index=4)
thirty_day_fig = plt.figure(figsize=(8,4))
plt.plot(thirty_day_data)
canvas = FigureCanvasTkAgg(thirty_day_fig, master=thirty_day_graph_frame)
plot_widget = canvas.get_tk_widget()
plot_widget.place(x=0,y=0)
five_year_fig=plt.figure(figsize=(8,4))
plt.plot(five_year_data)
canvas1=FigureCanvasTkAgg(five_year_fig, master=five_yrs_graph_frame)
plot_widget1=canvas1.get_tk_widget()
plot_widget1.place(x=1,y=0)
root.after(5000, stock_info, stock_name)
apple_button=Button(root,text='AAPL', command=lambda:stock_info('AAPL'))
tesla_button=Button(root,text='TSLA', command=lambda:stock_info('TSLA'))
google_button=Button(root,text='GOOG', command=lambda:stock_info('GOOG'))
apple_button.place(x=10, y=15)
tesla_button.place(x=10, y=45)
google_button.place(x=10,y=75)
root.mainloop()
The reason your graphs are plotted from the start is because of the way you assign commands to your buttons. One way to fix this is to assign the command as a lambda expression:
apple_button = Button(root, text='AAPL', command=lambda:stock_info('AAPL'))
To let your GUI update itself over time, you can create a loop using the root.after() method:
# Define the figure and canvas outside the loop
fig = plt.Figure()
a = fig.add_subplot(111)
canvas = FigureCanvasTkAgg(fig, master=f1)
canvas.get_tk_widget().grid()
def stock_info(stock_name):
# Get stock data and plot it on the GUI
...
a.cla()
a.plot(data)
canvas.draw()
# Schedule the function to call itself again after 5 seconds
root.after(5000, stock_info, stock_name)
Hi so I am using matplot lib in my django project. And I am able to embed a graph in my template/webpage. I need some help now on being able to animate a graph.
The graph is stored as a csv file with the location in my model. I want the graphs to be built dynamically. Now I have that. But I want them to be an animation. How would I go about doing this? I have to use matplotlib btw.
I assume make a video? I've seen people embed videos, but I was hoping to using the actual animation features of matplotlib such as:
http://pythonprogramming.net/python-matplotlib-live-updating-graphs/
Here is how I render the graph in my view:
def render_graph(request, graph_id=None):
graph = get_object_or_404(models.Graph, pk=graph_id) #grabs actual graph
data = np.genfromtxt(graph.data, delimiter=',', names=['x','y']) #extract data from cvs after x and y
fig = Figure()
ax = fig.add_subplot(111)
ax.plot(data['x'], data['y'], label=graph.name)
canvas=FigureCanvas(fig)
response = HttpResponse(content_type='image/png')
canvas.print_png(response)
return(response)
have you considered using d3 (d3js.org)? Might give better results.
I wrote a script which animates the results I obtained, using matplotlib.
Besides the animation I got, I wanted to save the figure at the final step of the animation; just before the animation is repeated. I defined a save-flag, to avoid the figure being saved over and over. You can see the simplified version of my code below:
#!/usr/bin/env python
import numpy as np
from matplotlib import pyplot as plt
import matplotlib.animation as animation
x = np.array(range(12))
y = np.array([i**2 for i in range(12)])
fig = plt.figure()
ax = plt.axes(xlim = (0,15), ylim = (0,150))
line, = ax.plot([],[], 'o-')
def init():
line.set_data([], [])
return line,
save_flag = False
def animate(i):
i = (i+1)%(len(x)+1)
line.set_data(x[0:i], y[0:i])
global save_flag
if (save_flag == False) and (i == (len(x)-1)):
print "\nThe figure is being saved!\n"
fig.savefig("foo" + ".png")
save_flag = True
return line,
ani = animation.FuncAnimation(fig, animate, repeat=True, blit=True, init_func=init)
plt.show()
If you run the script, you will probably see that, at the end of the first loop, the the animation becomes erroneous. This error is due to the blit, which is set True. However, if it is set to False, then the figure repeats itself as it should be.
Why is there such a problem; could it be a bug? (My Python version is 2.7.5+.)
Is there a better way to save a figure at the end of an animation?