Why doesn't x_range_type 'datetime' work with just one glyph/data point? - bokeh

I am using 'datetime' as the x_axis_type parameter in my plot figure. It works perfectly when there are multiple glyphs on my plot.
However, when I make another plot with only one glyph, the x ticker shows as (mili?) seconds rather than a datetime despite the x_axis_type remaining the same.
Surely there is a simple fix I don't know about?
Thank you in advance.
Full (ipynb) code:
from bokeh.plotting import figure, show
from bokeh.io import output_notebook
import pandas as pd
output_notebook()
df = pd.read_csv('my_data.csv')
df['Created'] = pd.to_datetime(df['Created'], utc=True)
plot = figure(x_axis_type='datetime')
plot.circle(df['Created'], df['Incident Duration MTTR Mins'])
show(plot)
# Second plot, this time only with one glyph
plot2 = figure(x_axis_type='datetime')
plot2.circle(df['Created'][0], df['Incident Duration MTTR Mins'][0])
show(plot2)

I've managed a solution:
from bokeh.models import DatetimeTickFormatter
...
plot2.xaxis.formatter=DatetimeTickFormatter(microseconds=["%Y-%m-%d"])

That's because the default range is an instance of DataRange1d, and if you don't have enough points for it to determine the span of the data, it will use the default value 2 (milliseconds, in this case).

Related

Multiple classes, unable to return desired page(s)

first want to say that I am a first time poster so I am sorry in advance if any parts of my question or the way it is asked/presented "sucks." With that being said, I've been trying to scrape a table from barchart.com use jupyter and beautifulsoup that is on multiple pages and while I have been successful in returning the entire page as a whole, I haven't had much luck trying to return the specific pages I need. I did include some images, the first three of which reference the elements that I am currently "choosing" from to use:
the 'div' element that highlights the entire table
another 'div' element within the first 'div' that also has the entire table I need
The 'table' element that I would use but it doesn't include the left most column that includes the tickers/stock symbols
Regardless of what I have tried to put in my code, I always get a "[]" back and haven't been able to figure out how to write the multiple parts of each 'div' or 'table', if that makes sense.
Code pic
from bs4 import BeautifulSoup as soup
from urllib.request import urlopen, Request
stonks_url = Request('https://www.barchart.com/options/unusual-activity/stocks', headers={'User-Agent': 'Mozilla/5.0'})
stonks_data = urlopen(stonks_url)
stonks_html = stonks_data.read()
stonks_data.close()
page_soup = soup(stonks_html, 'html.parser')
uoa_table = page_soup.findAll('tbody', {'data-ng-repeat': 'rows in content'})
print(uoa_table)
Thanks in advance to any advice or guidance!
As this page is not working with javascript request you need to use the selenium and get the page source of the page and use it for processing the table
from bs4 import BeautifulSoup
from urllib.request import urlopen, Request
from selenium import webdriver
driver= webdriver.Chrome()
driver.get('https://www.barchart.com/options/unusual-activity/stocks')
soup = BeautifulSoup(driver.page_source, 'html.parser')
# get text
text = soup.get_text()
print(text)

How to control Ipyvuetify ProgressCircular

I want to use an ipyvuetify widget called ProgressCircular to show the loading process. Therefore, I was trying to figure out how to show and hide the widget in my code.
progress=v.ProgressCircular(width=3,
color='red',
indeterminate=True,
)
Although I was able to see all the attributes with dir(), I still couldn't find the right one to use. How do people figure out how to use classes or functions in a package that lacks samples.
dir(v.ProgressCircular)
You can use display(progress) within an ipywidgets Output widget.
import ipyvuetify as v
import ipywidgets as ipyw
import time
progress=v.ProgressCircular(width=3,
color='red',
indeterminate=True,
)
output = ipyw.Output()
display(output)
with output:
display(progress)
time.sleep(2)
output.clear_output()
I will assume that you are working in a Jupyter environment :
after declaring your widget place it on the last line of your cell or use display as suggested by #ac24:
progress = v.ProgressCircular(
width = 3,
color = 'red',
indeterminate = True
)
progress
# alternatively
# display(progress)
once it's done you can play with it using some very basic html attributes
progress.class_ = 'd-none' # disapear
progress.class_ = None # shown
As you were complaining about the documentation, see here for the usage of HTML attributes https://ipyvuetify.readthedocs.io/en/latest/usage.html#setting-attributes, more examples would be useless as the possible combinations of html attributes are virtually infinite. Lucky for us vuetify.js is providing a very complete one that can be used in combination with the ipyvuetify one :
https://vuetifyjs.com/en/styles/display/
No need to use Output or styles for this, just make a container widget and change its children:
import ipyvuetify as v
import time
progress=v.ProgressCircular(width=3,
color='red',
indeterminate=True,)
container = v.Html(tag='div', children=[progress])
display(container)
time.sleep(2)
container.children=[v.Chip(children=['Done'])]

Is there a way to expand groups with the XDSM diagram creation in OpenMDAO?

Most of my test files involve the creation of an IndepVarComp that gets connected to a group. When I go to create an XDSM from the test file, it only shows the IndepVarComp Box and the Group Box. Is there a way to get it to expand the group and show what's inside?
This would also be useful when dealing with a top level model that contains many levels of groups where I want to expand one or two levels and leave the rest closed.
There is a recurse option, which controls if groups are expanded or not. Here is a small example with the Sellar problem to explore this option. The disciplines d1 and d2 are part of a Group called cycle.
import numpy as np
import openmdao.api as om
from openmdao.test_suite.components.sellar import SellarNoDerivatives
from omxdsm import write_xdsm
prob = om.Problem()
prob.model = model = SellarNoDerivatives()
model.add_design_var('z', lower=np.array([-10.0, 0.0]),
upper=np.array([10.0, 10.0]), indices=np.arange(2, dtype=int))
model.add_design_var('x', lower=0.0, upper=10.0)
model.add_objective('obj')
model.add_constraint('con1', equals=np.zeros(1))
model.add_constraint('con2', upper=0.0)
prob.setup()
prob.final_setup()
# Write output. PDF will only be created, if pdflatex is installed
write_xdsm(prob, filename='sellar_pyxdsm', out_format='pdf', show_browser=True,
quiet=False, output_side='left', recurse=True)
The same code with recurse=False (d1 and d2 are not shown, instead their Group cycle):
To enable the recursion from the command line, use the --recurse flag:
openmdao xdsm sellar_pyxdsm.py -f pdf --recurse
With the function it is turned on by default, in the command line you have to include the flag. If this does not work as expected for you, please provide an example.
You can find a lot of examples with different options in the tests of the XDSM plugin. Some of the options, like recurse, include_indepvarcomps, include_solver and model_path control what is included in the XDSM.

Creating a graph with images as nodes

I'm creating a graph with nodes as images,
# image from http://matplotlib.sourceforge.net/users/image_tutorial.html
I want to create a circular layout, with node zero positioned at the center.Egdelist is [(0,1),(0,2),(0,3),(0,4),(0,5)]
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import networkx as nx
img=mpimg.imread('stinkbug.png')
G=nx.complete_graph(6)
G.node[0]['image']=img
G.node[1]['image']=img
G.node[2]['image']=img
G.node[3]['image']=img
G.node[4]['image']=img
G.node[5]['image']=img
print(G.nodes())
G.add_edge(0,1)
G.add_edge(0,2)
G.add_edge(0,3)
G.add_edge(0,4)
G.add_edge(0,5)
print(G.edges())
nx.draw_circular(G)
But, in the output I find additional edges(snapshot attached).Is there a way to remove these additional edges? I want only these conncetions Egdelist is [(0,1),(0,2),(0,3),(0,4),(0,5)].Also, the original image is not displayed in the nodes.
Any suggestions?
so there are really two questions in here. The first is why your graph has more edges than you want. This happened because you used nx.complete_graph(6) to initialize your graph - which creates a complete graph on 6 nodes. You should rather initialize an empty graph, add nodes with the image metadata, then add edges.
To have nodes drawn as your image, I found and slightly adapted code from this discussion. It has a few things you can customize, such as the image size. The result is:
Hope this helps!
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import networkx as nx
img=mpimg.imread('/Users/johanneswachs/Downloads/stink.jpeg')
G=nx.Graph()
G.add_node(0,image= img)
G.add_node(1,image= img)
G.add_node(2,image= img)
G.add_node(3,image= img)
G.add_node(4,image= img)
G.add_node(5,image= img)
print(G.nodes())
G.add_edge(0,1)
G.add_edge(0,2)
G.add_edge(0,3)
G.add_edge(0,4)
G.add_edge(0,5)
print(G.edges())
pos=nx.circular_layout(G)
fig=plt.figure(figsize=(5,5))
ax=plt.subplot(111)
ax.set_aspect('equal')
nx.draw_networkx_edges(G,pos,ax=ax)
plt.xlim(-1.5,1.5)
plt.ylim(-1.5,1.5)
trans=ax.transData.transform
trans2=fig.transFigure.inverted().transform
piesize=0.2 # this is the image size
p2=piesize/2.0
for n in G:
xx,yy=trans(pos[n]) # figure coordinates
xa,ya=trans2((xx,yy)) # axes coordinates
a = plt.axes([xa-p2,ya-p2, piesize, piesize])
a.set_aspect('equal')
a.imshow(G.node[n]['image'])
a.axis('off')
ax.axis('off')
plt.show()

pyqtgraph, how track log/linear axes transformation changes between linked axes

I have 3 linked views, linked by X axis. This works great. However, when I switch one plot to log X mode, the others do not switch to log x mode, but they pop in to zoom way in to the log version of the x axis.
How do it make it so the log X transformation applies to all plots?
So far, I simply use the code
diViewWidget.setXLink(frViewWidget)
noiseViewWidget.setXLink(diViewWidget)
The data should look like this:
but actually look like this:
Basically, to reproduce you can go to any 2 linked views, right click and set the transformation to log x.
The workaround I found is to go to each plot individually and set the transformation individually, but I'd like it to happen programatically.
Thanks,
-Caleb
#learning qt i just found a better linkLogXChecks version
from itertools import permutations
def linkLogXChecks(plotitems):
for a, b in permutations(plotitems, 2):
a.ctrl.logXCheck.toggled.connect(b.ctrl.logXCheck.setChecked)
https://groups.google.com/forum/#!msg/pyqtgraph/3686qqVHgpI/bmBAQ_sDKJIJ
https://forum.qt.io/topic/39241/how-to-set-logarithmic-scale-on-a-qgraphicsview/2
I couldn't apply that fix across separate PlotItems, so tried broadcasting the changed checkbox signal and it seems to work
import pyqtgraph as pg
data = pg.np.random.normal(size=100)
app = pg.QtGui.QApplication([])
win = pg.GraphicsWindow()
p1 = win.addPlot(y=data)
win.nextRow()
p2 = win.addPlot(y=data)
p2.setXLink(p1)
win.nextRow()
p3 = win.addPlot(y=data)
p3.setXLink(p1)
def linkLogXChecks(plotitems):
def broadcast(state):
for p in plotitems:
p.ctrl.logXCheck.setChecked(state)
for p in plotitems:
p.ctrl.logXCheck.toggled.connect(broadcast)
linkLogXChecks([p1, p2, p3])
pg.QtGui.QApplication.instance().exec_()

Resources