Plotting only specific points using matplotlib's imshow
import numpy as np
import matplotlib.pyplot as plt
N = 101
x = np.linspace(1,1,N); ones = np.ones_like(x)
coords = np.outer(ones,x) #x coords
coords = np.concatenate([[coords], [coords.T]])
ourShape = np.zeros([N,N])
ourShape[np.square(coords[0,:,:]) + np.square(coords[1,:,:]) <= 1.] = 1.
fig, ax = plt.subplots();
ax.imshow(ourShape)
plt.show()
This plots a circle inscribed in a square. But how do I get python to plot only the blue region, which is part of the square and not the circle? To be clear, I do not want to just turn the circle white; I want it to not plot at all. I tried
ax.imshow(ourShape[ourShape < 1.])
and that produces a TypeError.
See also questions close to this topic

Keras Lambda Layer Before Embedding: Use to Convert Text to Integers
I currently have a
keras
model which uses anEmbedding
layer. Something like this:input = tf.keras.layers.Input(shape=(20,) dtype='int32') x = tf.keras.layers.Embedding(input_dim=1000, output_dim=50, input_length=20, trainable=True, embeddings_initializer='glorot_uniform', mask_zero=False)(input)
This is great and works as expected. However, I want to be able to send text to my model, have it preprocess the text into integers, and continue normally.
Two issues:
1) The Keras docs say that Embedding layers can only be used as the first layer in a model: https://keras.io/layers/embeddings/
2) Even if I could add a
Lambda
layer before theEmbedding
, I'd need it to keep track of certain state (like a dictionary mapping specific words to integers). How might I go about this stateful preprocessing?In short, I need to modify the underlying Tensorflow DAG, so when I save my model and upload to ML Engine, it'll be able to handle my sending it raw text.
Thanks!

PySpark: Sort or OrderBy DataFrame Column *Numerically* not working correctly
I have some fitness data that I'm trying to sort numerically, however the results are not turning out as the manual, and other examples, e.g. Spark DataFrame groupBy and sort in the descending order (pyspark), show:
display(df.sort(col("Calories Burned").desc()))#fails to sort correctly, shows 876, then 4756, display(df.orderBy("Calories Burned", ascending = False))#fails to sort correctly, shows 876, then 4756 display(df.sort(desc("Calories Burned")))
All these examples display the following two columns data (there are more columns, but I'm abbreviating for space):
Date Calories Burned 20181018 876 20180526 4756 20180505 4440
As you can see, these are not sorting numerically. Spark isn't taking the number of digits into account, so 876 appears before 4756.
Whether or not I include the
col
function makes no difference, either.How can this dataset be sorted numerically so the data looks more like this?
Date Calories Burned 20180526 4756 20180505 4440 20181018 876

Turtle is not reacting to onkeypress [SOLVED]
So, I am new in python so I took some time and watched some videos about how to make a simple "snake" game, I was doing everything that dude was saying, but when it came to the keyboard binding something went wrong and I can't move my turtle..
code:
https://pastebin.com/GLSRNKLRimport turtle import time delay = 0.1 # Screen wn = turtle.Screen() wn.title("Snake Game By AniPita") wn.bgcolor('black') wn.setup(600, 600) wn.tracer(0) # Snake Head head = turtle.Turtle() head.speed(0) head.shape("square") head.color("white") head.penup() head.goto(0, 0) head.direction = "stop" # Functions def go_up(): head.direction == "up" def go_down(): head.direction == "down" def go_left(): head.direction == "left" def go_right(): head.direction == "right" def move(): if head.direction == "up": y = head.ycor() head.sety(y + 10) if head.direction == "down": y = head.ycor() head.sety(y  10) if head.direction == "left": x = head.xcor() head.setx(x  10) if head.direction == "right": x = head.xcor() head.setx(x + 10) # Keyboard Bindings wn.onkeypress(go_up(), 'w') wn.onkeypress(go_down(), 's') wn.onkeypress(go_left(), 'a') wn.onkeypress(go_right(), 'd') wn.listen() # Main Game while True: wn.update() time.sleep(delay) move() wn.mainloop()

Matplotlib blitting multiple artists
I'm trying to create an annimated Matplotlib chart that uses blitting. I would like to include, a scatter plot, line plots, and annotations all in the same subplot. However, all the examples I have found, e.g., https://matplotlib.org/gallery/animation/bayes_update.html seem to only return a single artist, e.g., just a line plot. (I think I'm using the artist term correctly, but may not be.)
I've tried to wrap multiple artists together but that seems not to work. For example in the below, the plot line does not get updated and if blit is set to True I get an AttributeError: 'Artists' object has no attribute 'set_animated'
from collections import namedtuple import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation fig, ax = plt.subplots() Artists = namedtuple('Artists', ('scatter', 'plot')) artists = Artists( ax.scatter([], []), ax.plot([], [], animated=True)[0], ) def init(): ax.set_xlim(1, 1) ax.set_ylim(1, 1) return artists, def update(frame): artists.scatter.set_offsets([[0, 0]]) artists.plot.set_data([0, 1], [0, 1]) return artists, ani = FuncAnimation( fig=fig, func=update, init_func=init, blit=True) plt.show()
What is the right way to do blitting with multiple artists?

matplotlib.pyplot.axvline Label did not appear when use axvline function
I'm writing a function to plot histogram using
matplotlib
I am trying to add vertical line inmean, mean+2*sd, and mean2*sd
. The lines appears on the plot but the label I'm giving to them does not, any idea how to fix that?Also I am trying to put this text
Mean = "for example x"
But I am using hard coded coordinationplt.text(400, 0.015, "Mean = {}".format(round(mean, 3)))
How can I use programmatic way to infer the values for the coordinate? same in thin line:plt.axis([min(data), max(data), 0, 0.02])
Can I get min and max Y values in a more efficient way instead of hard coding them?def hist(location, data, mean, std, n_bins=20, x_label="", y_label="", title=""): samples = sorted(data) x = np.linspace(min(samples), max(samples), 12) y_pdf = stats.norm.pdf(x, mean, std) y_skew_pdf = stats.skewnorm.pdf(x, *stats.skewnorm.fit(samples)) l1, = plt.plot(x, y_pdf, label='PDF') l2, = plt.plot(x, y_skew_pdf, label='SKEW PDF') # Compute histogram of Samples n, bins, patches = plt.hist(samples, n_bins, density=True, facecolor='g', edgecolor='red', alpha=0.75) plt.axvline(label='Mean', x=mean, linestyle=':', color='red') plt.axvline(label='Mean2*SD', x=round(mean2*std, 3), linestyle='dashed') plt.axvline(label='Mean+2SD', x=round(mean+2*std, 3), linestyle='dashed') plt.xlabel(x_label) plt.ylabel(y_label) plt.title(title) # The first plt.text arguments are coordinates x,y of the plot plt.text(400, 0.015, "Mean = {}".format(round(mean, 3))) plt.legend((l1, l2), (l1.get_label(), l2.get_label()), loc='upper right') plt.axis([min(data), max(data), 0, 0.02]) plt.savefig(location)

Plotting data month wise
I have to plot a months the number of reviews and average of rating by month after May 2015.`
review_id date rating 4962_66 1/1/14 5.0 4962_105 1/5/14 5.0 4962_543 2/6/14 5.0 4962_267 8/11/14 5.0 4962_459 2/1/14 5.0
The dataset has about 5k rows in an unorganised manner. Trid something like this, but I guess this is wrong
plt.plot(May2015['date'].rolling(30), May2015.groupby('review_id').count().
May2015 is a df with values after the date May2015 to January 2018.

Efficient scatterplot with specific colors for each point using Matplotlib
I need to create a scatterplot in Python of N~10000 points where each point has a specific x, y, color and size. This is what I am creating. But the way I am doing it takes a very long time (~10 sec for 1000 points, ~2 min for 10000 points). This is a dummy code that represents what I am doing:
# x = [list of x coords] # y = [list of y coords] # colors = [list of color triples] # sizes = [list of marker sizes] f,ax = plt.figure() N = 10000 for i in range(N): ax.plot(x[i],y[i], marker='.', color=colors[i], markersize = sizes[i])
Using plt.scatterplot takes the same amount of time. Is there a better (faster) way of achieving the same result?

How would you recommend visually presenting an interaction term from a conditionally logistic regression?
I would like to plot the interaction term from a
coxph
model from thesurvival
package in r. I have triedinteract_plot
from thejtool
package, but I keep getting errors and suspect that interact_plot does not supportcoxph
objects.My model is
hiitime.coxph<coxph(formula=Surv(rep(1, 77748L), y) ~ log(x1+1)*x2+ strata(id) + cluster(id2),data = data, method = "breslow")
The response
y
is binomial andx1
andx2
are both continuous. What I need is a plot that visualises how the probability ofy
varies withx1
for different values ofx2
.Any recommendations other than
interact_plot
? 
Choosing right libraries for current Python school project
im new to python programming and i need help in choosing right libraries. I would like to create an app for raspberry to recieve data from microcontroller via gprs (apache server) store it on disk (sql) and make some graphical representation of these values. It will be a gyro values from sea buoy. So im thinking about some plot and moving buoy image. Do you suggest some specific libraries for that (or framework). Thanks in advance.