I am generating histograms using go.Histogram as described here. I am getting what is expected:
What I want to do is to show some statistics of the selected data, as shown in the next image (the white box I added manually in Paint):
I have tried this and within the function selection_fn I placed the add_annotation described here. However, it does nothing. No errors too.
How can I do this?
Edit: I am using this code taken from this link
import plotly.graph_objects as go
import numpy as np
x = np.random.randn(500)
fig = go.Figure(data=[go.Histogram(x=x)])
fig.show()
with obviously another data set.
Related
I am trying to make a palettized version of my height image data (using Python/Matplotlib) and for some reason...it is giving me quite weird horizontal lines which I know are not actually present in the dataset.
Both images (mine and the "better" one).
Is this something weird with how Matplotlib normalizes the data? I just don't quite understand how this could happen, so I am at a loss for where to start. I have provided my code below (sorry if there is a typo, I slightly changed it to make sense outside of the code).
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# file location of the raw data
fileloc = r'C:\Users\...\raw_height_profile.csv'
# generate height profile map
palettized_image = getheightprofile(fileloc)
def getheightprofile(fileloc, color_palette='jet'):
# read data from file
data = pd.read_csv(fileloc, skiprows=0)
# generate colormap (I'm using the jet colormap rn)
colormap = plt.get_cmap(color_palette)
# normalize the height data to the range [0, 1]
norm = (data - np.min(data)) / (np.max(data) - np.min(data))
# convert the height data to RGB values using the palette
palettized_data = (colormap(norm)*255).astype(np.uint8)
# save the file as a png (to check quality)
saveloc = r'C:\Users\...\palletized_height_profile.png'
plt.imsave(saveloc, palettized_data)
# return the nice numbers for later analysis
return palettized_data
But instead of returning the nice image that I think I should get, it returns a super weird image with lines across it. note: I know these images aren't quite the same palettization, but I think you can understand the issue.
Does anyone understand how, why, etc.? I have also attached a link to the dataset, because maybe that is helpful...but I am quite sure there is nothing wrong with the data.
I'm trying out Datashader on Google Colab to visualise a large dataset of longitudes and latitudes colored logarithmically with the colorcet.fire colormaps, but my code throws a completely blank output.
Code in text:
import datashader as ds
import pandas as pd
import colorcet
data = pd.read_csv('hab.csv', usecols=['longitude','latitude'])
cvs = ds.Canvas()
agg = cvs.points(data, 'latitude', 'longitude')
ds.tf.set_background(ds.tf.shade(agg, cmap=colorcet.fire, how='log'))
What I see on Colab:
I'm not a collab user, but yes, when I run your code locally with the five datapoints shown I get a blank plot. In my local version, it's because the code is specifying a colormap whose highest value is white, and for a few scattered points each of them are at the highest value. The code uses set_background, perhaps trying to set the background to black as would be suitable for that colormap, but it doesn't specify "black" and so the set_background call does nothing. If I specify the background color and add Datashader spreading so that these single datapoints are easier to see, I do get a plot from your code:
cvs = ds.Canvas()
agg = cvs.points(data, 'latitude', 'longitude')
ds.tf.set_background(ds.tf.shade(ds.tf.spread(agg, px=10), cmap=colorcet.fire, how='log'), "black")
You may have some other problem as well, though, since the plot you showed wasn't just white, it appeared to be transparent. And if your dataset is indeed large, you should see output anyway, because data points would then overlap and use all the colors in the colormap.
I tried the following example 3D Mesh example with AlphaNull to test alphahull but my jupyter notebook display just something blank.
When I set alphahull=5, the display is blank:
But when i set alphahull = 0, it works:
and when i set alphahull = -1, it works :
Why is this happening and how can I fix it?
Thank you in advance for your help.
Unfortunately I think rendering for alphahull values larger than 0 may be broken as of the latest plotly update. I noticed that in the documentation page, their code example with alphahull=5 also doesn't render. I tried with other positive values and none of these render either (the same alpha shape algorithm is used for any alphanull > 0)
However, I tried downgrading to plotly==4.14.0 and the same example with alphahull=5 does render.
import plotly.graph_objects as go
import numpy as np
pts = np.loadtxt(np.DataSource().open('https://raw.githubusercontent.com/plotly/datasets/master/mesh_dataset.txt'))
x, y, z = pts.T
fig = go.Figure(data=[go.Mesh3d(x=x, y=y, z=z,
alphahull=5,
opacity=0.4,
color='cyan')])
fig.show()
So in your jupyter notebook, you can run the line !pip install plotly==4.14.0 in a separate cell and see if that allows you to render positive alphahull values.
I'm working on taking some data from a dataset and plotting certain aspects of it. Here's my code below:
import matplotlib.pyplot as plt
df1 = pd.read_csv('dataset_1.csv')
soil_moisture = list(df1.Soil_Moisture)
soil_temperature = list(df1.Soil_Temp)
print(len(soil_moisture))
print(len(soil_temperature))
plt.plot([soil_moisture], [soil_temperature])
plt.show()
As you can see, it takes data from each of those columns and tries to make a line graph. However, when I run, it just displays an empty graph. This is weird since when I print the soil_moisture and soil_temperature, it tells me that there's actual data, and none of my other plots in the same notebook are experiencing this. All help is appreciated!
Here's an image of the jupyter output
Please revise line 7 of your code as:
plt.plot(soil_moisture, soil_temperature)
When you use [soil_moisture] that means you are generating another list with list soil_moisture as its first element.
The Problem:
I'm trying to simulate a live video by cycling through a series of still images I have saved in a directory, but when I add the animation and update functions my plot is displayed empty.
Background on why I'm doing this:
I believe its important for me to do it this way rather than a complete change of approach, say turning the images into a video first then displaying that, because what I really want to test is the image analysis I will be adding and then overlaying on each frame. The final application will be receiving frames one by one from a camera and will need to do some processing, display the image + annotations + output the data as .csv etc... I'm simulating this for now because I do not have any of the hardware to generate the images and will not have it for several months during which time I need to get the image processing set up, but I do have access to some sets of stills that are approximately what will be produced. In case its relevant my simulation images are 1680x1220 and are 1.88 Mb TIFFs, though I could covert and compress them if needed, and in the final form the resolution will be a bit higher and probably the image format could be adjusted if needed.
What I have tried:
I followed an example to list all files in a folder, and an example
to update a plot. However, the plot displays blank when I run the
code.
I added a line to print the current file name, and I can see this
cycling as expected.
I also made sure the images will display in the plot if I just create
a plot and add one image, and they do. But, when combined with the
animation function the plot is blank and I'm not sure what I've done
wrong/failed to include.
I also tried adding a plt.pause() in the update, but again this
didn't work.
I increased the interval up to 2000 to give it more time, but that didn't work. I believe 2000 is extreme, I'm expecting it should work with more like 20-30fps. Going to 0.5fps tells me the code is wrong or incomplete, rather than it just being a question of needing time to read the image file.
I appreciate no one else has my images, but they are nothing special. I'm using 60 images but I guess it could be tested with any 2 random images and setting range(60) to range(2) instead?
The example I copied originally demonstrated the animation function by making a random array, and if I do that it will show a plot that updates with random squares as expected.
Replacing:
A = np.random.randn(10,10)
im.set_array(A)
...with my image instead...
im = cv2.imread(files[i],0)
...and the plot remains empty/blank. I get a window shown called "Figure1" (like when using the random array), but unlike with the array there is nothing in this window.
Full code:
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import os
import cv2
def update(i):
im = cv2.imread(files[i],0)
print(files[i])
#plt.pause(0.1)
return im
path = 'C:\\Test Images\\'
files = []
# r=root, d=directories, f = files
for r, d, f in os.walk(path):
for file in f:
if '.TIFF' in file:
files.append(os.path.join(r, file))
ani = FuncAnimation(plt.gcf(), update, frames=range(60), interval=50, blit=False)
plt.show()
I'm a python and a programming novice so have relied on adjusting examples others have given online but I have only a simplistic understanding of how they are working and end up with a lot of trial and error on the syntax. I just can't figure out anything to make this one work though.
Cheers for any help!
The main reason nothing is showing up is because you never add the images to the plot. I've provided some code below to do what you want, be sure to look up anything you are curious about or don't understand!
import glob
import os
from matplotlib import animation
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
IMG_DIRPATH = 'C:\\Test Images\\' # the folder with your images (be careful about
# putting spaces in directory names!)
IMG_EXT = '.TIFF' # the file extension of your images
# Create a figure, and set to the desired size.
fig = plt.figure(figsize=[5, 5])
# Create axes for the current figure so that images can be sized appropriately.
# Passing in [0, 0, 1, 1] makes the axes fill the whole figure.
# frame_on=False means we won't have a bounding box, and setting xticks=[] and
# yticks=[] means that we won't have pesky tick marks along our image.
ax_props = {'frame_on': False, 'xticks': [], 'yticks': []}
ax = plt.axes([0, 0, 1, 1], **ax_props)
# Get all image filenames.
img_filepaths = glob.glob(os.path.join(IMG_DIRPATH, '*' + IMG_EXT))
def update_image(img_filepath):
# Remove all existing images on the axes, and restore our settings.
ax.clear()
ax.update(ax_props)
# Read the current image.
img = mpimg.imread(img_filepath)
# Add the current image to the plot axes.
ax.imshow(img)
anim = animation.FuncAnimation(fig, update_image, frames=img_filepaths, interval=250)
plt.show()