Right orientation with z up - vpython

how to make axis x,y,z look like
from visual import *
f = frame()
# Axis
pointer_x = arrow(frame=f, pos=(0,0,0), axis=(40,0,0), shaftwidth=1, color = color.red)
pointer_y = arrow(frame=f, pos=(0,0,0), axis=(0,40,0), shaftwidth=1, color = color.blue)
pointer_z = arrow(frame=f, pos=(0,0,0), axis=(0,0,40), shaftwidth=1, color = color.green)
# Show X,Y,Z labels
label(frame=f,pos=(40,0,0), text='X')
label(frame=f,pos=(0,40,0), text='Y')
label(frame=f,pos=(0,0,40), text='Z')

This code solved it, if there is better approach comment it.
# Show it like ECEF
f.rotate(angle=radians(-90),axis=(1,0,0),origin=(0,0,0))
f.rotate(angle=radians(180),axis=(0,1,0),origin=(0,0,0))

Related

How to set different color every gene and add legend in ChromoMap using R studio?

I have plot my data to make gene position in chromosome using chromoMap.
here
chr file
chr anot file
and these are my scripts
library(chromoMap)
col.set = c("purple", "#4CBB17","#0096FF", "blue", "brown")
chr.data <- read.csv("chr_file.csv", header=T)
anno.data <- read.csv("chr_anot.csv", header = T)
chromoMap(list(chr.data),list(anno.data), labels = T, data_based_color_map = T,
data_color = list(c(col.set)))
I got the result like this
output file
I would like to set every gene with different color and add the legend.
Any idea what should I do? Please help me.
Thank you
In order to color each gene with a unique color you just need to add a 5th data column to your annotations data anno.data lets say the names of your genes like:
anno.data <- cbind.data.frame(anno.data,Symbol=anno.data$element)
and then each of your gene will have the unique color. Also, for the legend you just need to set the legend argument to true.
here is the code with some additional configuration options for your plot:
chromoMap(list(chr.data),list(anno.data),
# labelling arguments
labels = T,
label_font = 12,
label_angle = -55,
# group annotation arguments
data_based_color_map = T,
data_type = "categorical",
data_colors = list(c(col.set)),
# for the legend
legend = T,
#adjusting the legend along y-axis
lg_y = 250,
#increasing canvas width for legend
canvas_width = 600,
#playing with plot properties
text_font_size = 12,
chr_color = c("#d3d3d3"))
Thanks & Regards,
Lakshay(chromoMap developer)

Hide the grid in an a specificaltair plot within a set of vstacked plots

I am trying to create a plot composed of 2 charts stacked vertically: a time series chart showing a data and below it a time series chart showing texts representing events on the time axis. I want the data-chart having a grid, but the mark_text chart below not to show an outer line and no grid. I use the chart.configure_axis(grid=False) command to hide the axis but get the following error: Objects with "config" attribute cannot be used within LayerChart. Consider defining the config attribute in the LayerChart object instead.
I can't figure out, where to apply the configure_axis(grid=False) option, so it will only apply to the bottom plot. any help on this would be greatly appreciated. or any suggestion how to implement the label-plot in a different way.
here is my code:
import altair as alt
import pandas as pd
import locale
from altair_saver import save
from datetime import datetime
file = '.\lagebericht.csv'
df = pd.read_csv(file, sep=';')
source = df
locale.setlocale(locale.LC_ALL, "de_CH")
min_date = '2020-02-29'
domain_pd = pd.to_datetime([min_date, '2020-12-1']).astype(int) / 10 ** 6
base = alt.Chart(source, title='Neumeldungen BS').encode(
alt.X('test_datum:T', axis=alt.Axis(title="",format="%b %y"), scale = alt.Scale(domain=list(domain_pd) ))
)
bar = base.mark_bar(width = 1).encode(
alt.Y('faelle_bs:Q', axis=alt.Axis(title="Anzahl Fälle"), scale = alt.Scale(domain=(0, 120)))
)
line = base.mark_line(color='blue').encode(
y='faelle_Total:Q')
chart1 = (bar + line).properties(width=600)
events= pd.DataFrame({
'datum': [datetime(2020,7,1), datetime(2020,5,15)],
'const': [1,1],
'label': ['allgememeiner Lockdown', 'Gruppen > 50 verboten'],
})
base = alt.Chart(events).encode(
alt.X('datum:T', axis=alt.Axis(title="", format="%b %y"), scale = alt.Scale(domain=list(domain_pd) ))
)
points = base.mark_rule(color='blue').encode(
y=alt.Y('const:Q', axis=alt.Axis(title="",ticks=False, domain=False, labels=False), scale = alt.Scale(domain=(0, 10)))
)
text = base.mark_text(
align='right',
baseline='bottom',
angle = 20,
dx=0, # Nudges text to right so it doesn't appear on top of the bar
dy=20,
).encode(text='label:O').configure_axis(grid=False)
chart2 = (points + text).properties(width=600, height = 50)
save(chart1 & chart2, r"images\figs.html")
this is what it looks without the grid=False option:
enter image description here
The configure() method should be thought of as a way to specify a global chart theme; you cannot have different configurations within a single Chart (See https://altair-viz.github.io/user_guide/customization.html#global-config-vs-local-config-vs-encoding for a discussion of this).
The way to do what you want is not via global configuration, but via axis settings. For example, you can pass grid=False to alt.Axis:
points = alt.Chart(events).mark_rule(color='blue').encode(
x=alt.X('datum:T', axis=alt.Axis(title="", format="%b %y"), scale = alt.Scale(domain=list(domain_pd) )),
y=alt.Y('const:Q', axis=alt.Axis(title="",ticks=False, domain=False, labels=False), scale = alt.Scale(domain=(0, 10)))
)
text = alt.Chart(events).mark_text().encode(
x=alt.X('datum:T', axis=alt.Axis(title="", grid=False, format="%b %y"), scale = alt.Scale(domain=list(domain_pd) )),
text='label:O'
)

Plot multi label (values) with multi bar chart

I've this issue I hope you can help.
I've this data :
to_stack = pd.DataFrame([['CHILDREN', 0.42806248287201976, 0.0],
['AMT_TOTAL', 165006, 179357],
['SAL', 582065, 703917.0],
['ANNUITY', 26851, 28416]], columns=('Variable','Id','Mean'))
When I run the code below
to_stack.plot.barh(x='Variable', figsize=(12,8), width = .9)
## First Loop for first Variable "ID"
for index,value in enumerate(to_stack['Id']):
plt.text(value, index, str(value), va='top', )
## Second Loop for Second Variable
for i,val in enumerate(to_stack['Mean']):
plt.text(val, i, str(val), va='bottom' )
I get this result
The Values in each bar ar not well centralized
I've tried several options in Matplotlib.plt.text (ha (center, left, right) , va (top, bottom, baseline) without good results, sometimes it's even worse, values are one on each other.
How can we get the values aligned with the bars ?
Any ideas are really welcome
It's better to extract information from the bars and annotate. That way, you have more control of how the text appears in relative to the bars:
fig, ax = plt.subplots(figsize=(12,8),)
to_stack.plot.barh(x='Variable', width = .9, ax=ax)
for patch in ax.patches:
w, h = patch.get_width(), patch.get_height()
y = patch.get_y()
ax.text(w + -0.1,h/2+y, f'{w:.3f}', va='center')
Output:

How can I plot a 3D wireframe in Excel?

using Excel interface, how can I plot a 3D wireframe? I have no clue how to do this ! but wanted to do by giving the coordinates of the joints where there are frames between them.
for simplicity of the Example, just immagine a 3D wireframe in the form of a cube.
Ok, so I previously gave advice as to switch on the macro recorder but this would not give you the 3D mathematics required to draw wireframes. For that you need a library, Philip Rideout's SVG wireframes Python library which is written up here on his blog.
On my blog I have added some code which parses the SVG file generated by Philip Rideout's code and then converts the Polygon directives to Excel free from shapes on the worksheet. This is a screenshot of the output.
I have added the code here as well
class ScreenUpdatingRAII(object):
def __init__(self, app, visible:bool=False):
self.app = app
self.saved = app.ScreenUpdating
app.ScreenUpdating = visible
def restore(self):
self.app.ScreenUpdating = self.saved
self.app = None
def convertSvgToExcelShapes(filename):
import xml.etree.ElementTree as ET
from win32com.client import GetObject,Dispatch
# code below is highly dependent on the child
# structure because xpath was not working for me (my bad)
dom = ET.parse(filename)
rootxml = dom.getroot()
g = rootxml[1] # second child
wb = Dispatch(GetObject(r"C:\Users\Simon\source\repos\WireframeExcelShapes\WireframeExcelShapes\WireframeExcelShapes.xlsx"))
app = Dispatch(wb.Parent)
ws = Dispatch(wb.Worksheets.Item("WireFrame"))
shps = Dispatch(ws.Shapes)
for x in shps:
Dispatch(x).Delete()
idx =0
scale, xoffset, yoffset = 500, 300,300
screenUpdates = ScreenUpdatingRAII(app)
for polygon in g:
# triple nested list comprehension parsing the points by splitting
# first by space then by comma then converting to float
points = [[float(z[0])*scale+xoffset, float(z[1])*scale+yoffset] for z in [y.split(',') for y in [x for x in polygon.attrib['points'].split()]]]
#print(points)
msoEditingAuto,msoSegmentLine, msoFalse, msoTrue = 0,0,0, -1
freeformbuilder=shps.BuildFreeform(msoEditingAuto, points[0][0] , points[0][1])
freeformbuilder.AddNodes(msoSegmentLine, msoEditingAuto, points[1][0] , points[1][1])
freeformbuilder.AddNodes(msoSegmentLine, msoEditingAuto, points[2][0] , points[2][1])
freeformbuilder.AddNodes(msoSegmentLine, msoEditingAuto, points[0][0], points[0][1])
newShp = Dispatch(freeformbuilder.ConvertToShape())
shpFill = Dispatch(newShp.Fill)
shpFill.Visible = msoTrue
shpFill.Transparency = 0.25
shpFill.Solid
shpFill.ForeColor.RGB = 0xFFFFFF
idx=+1
screenUpdates.restore()
pass
filename = "octahedron.svg"
generate_svg(filename)
convertSvgToExcelShapes(filename)
You still have a little work to do to generate your own shape as the sample shape is an octahedron.

How to reduce image portion with numpy.compress method ? (numpy+scikit-image)

Hi using the sample image phantom.png I'm following some operations with numpy + skimage libraries and after some modifications the last one exercise ask for:
Compress the size of center spots by 50% and plot the final image.
These are the steps I do before.
I read the image doing
img = imread(os.path.join(data_dir, 'phantom.png'))
Then apply following to make it black and white
img[np.less_equal(img[:,:,0],50)] = 0
img[np.greater_equal(img[:,:,0],51)] = 255
Took couple of slices of the image (the black spots) with given coordinates
img_slice=img.copy()
img_slice=img_slice[100:300, 100:200]
img_slice2=img.copy()
img_slice2=img_slice2[100:300, 200:300]
Now flip them
img_slice=np.fliplr(img_slice)
img_slice2=np.fliplr(img_slice2)
And put them back into an image copy
img2=img.copy()
img2[100:300, 200:300]=img_slice
img2[100:300, 100:200]=img_slice2
And this is the resulting image before the final ("compress") excersise:
Then I'm asked to "reduce" the black spots by using the numpy.compress method.
The expected result after using "compress" method is the following image (screenshot) where the black spots are reduced by 50%:
But I have no clue of how to use numpy.compress method over the image or image slices to get that result, not even close, all what I get is just chunks of the image that looks like cropped or stretched portions of it.
I will appreciate any help/explanation about how the numpy.compress method works for this matter and even if is feasible to use it for this.
You seem ok with cropping and extracting, but just stuck on the compress aspect. So, crop out the middle and save that as im and we will compress that in the next step. Fill the area you cropped from with white.
Now, compress the part you cropped out. In order to reduce by 50%, you need to take alternate rows and alternate columns, so:
# Generate a vector alternating between True and False the same height as "im"
a = [(i%2)==0 for i in range(im.shape[0])]
# Likewise for the width
b = [(i%2)==0 for i in range(im.shape[1])]
# Now take alternate rows with numpy.compress()
r = np.compress(a,im,0)
# And now take alternate columns with numpy.compress()
res = np.compress(b,r,1)
Finally put res back in the original image, offset by half its width and height relative to where you cut it from.
I guess you can slice off the center spots first by :
center_spots = img2[100:300,100:300]
Then you can replace the center spots values in the original image with 255 (white)
img2[100:300,100:300] = 255
then compress center_spots by 50% along both axes and add the resultant back to img2
the compressed image shape will be (100,100), so add to img2[150:250,150:250]
Check the below code for the output you want. Comment if you need explanation for the below code.
import os.path
from skimage.io import imread
from skimage import data_dir
import matplotlib.pyplot as plt
import numpy as np
img = imread(os.path.join(data_dir, 'phantom.png'))
img[np.less_equal(img[:,:,0],50)] = 0
img[np.greater_equal(img[:,:,0],51)] = 255
img_slice=img[100:300,100:200]
img_slice2=img[100:300,200:300]
img_slice=np.fliplr(img_slice)
img_slice2=np.fliplr(img_slice2)
img2=img.copy()
img2[100:300, 200:300]=img_slice
img2[100:300, 100:200]=img_slice2
#extract the left and right images
img_left = img2[100:300,100:200]
img_right = img2[100:300,200:300]
#reduce the size of the images extracted using compress
#numpy.compress([list of states as True,False... or 1,0,1...], axis = (0 for column-wise and 1 for row-wise))
#In state list whatever is False or 0 that particular row should will be removed from that matrix or image
#note: len(A) -> number of rows and len(A[0]) number of columns
#reducing the height-> axis = 0
img_left = img_left.compress([not(i%2) for i in range(len(img_left))],axis = 0)
#reducing the width-> axis = 1
img_left = img_left.compress([not(i%2) for i in range(len(img_left[0]))],axis = 1)
#reducing the height-> axis = 0
img_right = img_right.compress([not(i%2) for i in range(len(img_right))],axis = 0)
#reducing the width-> axis = 1
img_right = img_right.compress([not(i%2) for i in range(len(img_right[0]))],axis = 1)
#clearing the area before pasting the left and right minimized images
img2[100:300,100:200] = 255 #255 is for whitening the pixel
img2[100:300,200:300] = 255
#paste the reduced size images back into the main picture(but notice the coordinates!)
img2[150:250,125:175] = img_left
img2[150:250,225:275] = img_right
plt.imshow(img2)
numpy.compress document here.
eyes = copy[100:300,100:300]
eyes1 = eyes
e = [(i%2 == 0) for i in range(eyes.shape[0])]
f = [(i%2 == 0) for i in range(eyes.shape[1])]
eyes1 = eyes1.compress(e,axis = 0)
eyes1 = eyes1.compress(f,axis = 1)
# plt.imshow(eyes1)
copy[100:300,100:300] = 255
copy[150:250,150:250] = eyes1
plt.imshow(copy)

Resources