spyder console doesn't output the values from script - console

I am trying to see the output of my code in spyder but it doesn't outputs. I am using spyder 3.3.6. Its just few lines of code as following:
import pandas as pd
x_y_data = pd.read_csv("x_y_points400_labeled_csv.csv")
x = x_y_data.loc[:,'x']
y = x_y_data.loc[:,'y']
x_length=len(x)
x_length
x
it doesn't show anything and no error,
but when i type in console, x or print(x) it does.
can you please help?

Related

heatmap in Julia : why is there a transpose between the terminal and the IDE?

I'm unsure why the heatmap outputed by the following minimal working example
using Plots
plotlyjs()
List_x = [1, 2, 3]
List_y = [1, 2]
List_f = [0 0 0; 1 2 3]
my_plot = heatmap(List_x, List_y, List_f,
xlabel = "x axis", ylabel = "y_axis")
display(my_plot)
readline()
depends on whether I run the code from my IDE (either VSCode or Atom), or from the terminal with
>>> julia MWE.jl
In the IDE case, I get
Figure produced by the MWE if run from IDE
And in the terminal case I get
Figure produced by the MWE if run from terminal
As you can see, there is a transpose between the two cases. I would like to always have the IDE behavior, can I do something about it?
This behavior was due to a bug reported in https://github.com/JuliaPlots/Plots.jl/issues/3940, fixed in https://github.com/JuliaPlots/Plots.jl/pull/3953, and released in Plots.jl v1.24.2. On the most recent version, the REPL (terminal) plot now looks like:

R autoplot works when running line-by-line but not when source-ing R script

I'm observing a very strange behaviour with R.
The following code works when I type it in line-by-line into an instance of R run from my terminal. (OS is Debian Linux.)
However it does not work when I try and run source("script.R").
It also does not work from within R Studio.
Specifically, it fails to produce graphical output with autoplot. Writing to pdf file does not work, and if I remove the pdf() and dev.off() lines, no window containing the figure is opened.
Here's a copy of my script...
library(lubridate)
library(ggplot2)
library(matrixStats)
library(forecast)
df_input <- read.csv("postprocessed.csv")
x <- df_input$time
y <- df_input$value
df <- data.frame(x, y)
x <- df$x
y <- df$y
holtmodel <- holt(y)
pdf("autoplot.pdf")
autoplot(holtmodel)
dev.off()
And for convenience, here's a datafile.
"","time","value"
"1",1,2.61066016308988
"2",2,3.41246054742996
"3",3,3.8608767964033
"4",4,4.28686048552237
"5",5,4.4923132964825
"6",6,4.50557049744317
"7",7,4.50944447661246
"8",8,4.51097373134893
"9",9,4.48788748823809
"10",10,4.34603985656981
"11",11,4.28677073671406
"12",12,4.20065901625172
"13",13,4.02514194962519
"14",14,3.91360194972916
"15",15,3.85865748409081
"16",16,3.81318053258601
"17",17,3.70380706527433
"18",18,3.61552922363713
"19",19,3.61405310598722
"20",20,3.64591327503384
"21",21,3.70234435835577
"22",22,3.73503970503372
"23",23,3.81003078640584
"24",24,3.88201196162666
"25",25,3.89872518158949
"26",26,3.97432743542362
"27",27,4.2523675144599
"28",28,4.34654855854847
"29",29,4.49276038902684
"30",30,4.67830892029687
"31",31,4.91896819673664
"32",32,5.04350767355202
"33",33,5.09073406942046
"34",34,5.18510849382162
"35",35,5.18353176529036
"36",36,5.2210776270173
"37",37,5.22643491929207
"38",38,5.11137006553725
"39",39,5.01052467981257
"40",40,5.0361056705898
"41",41,5.18149486951409
"42",42,5.36334869132276
"43",43,5.43053620818444
"44",44,5.60001072279525
Pretty confused because it seems like a trivial script!
change it to:
print(autoplot(holtmodel))
When you step through code, you get an implicit print(...) statement on each code line. When you source() you don't. ggplot (and others!) use print() to trigger their ploting (so that you can conveniently build up a plot step by step without having to wait for flickering figures)

Profiling in RStudio - profvis() not giving desired outputs

I am trying to learn how to profile in R, and am in need of some help. I am using the profvis() function, and am following the examples both in Chapter 7 of Colin Gillespie's Efficient R programming, and the Rstudio support page for profiling: https://support.rstudio.com/hc/en-us/articles/218221837-Profiling-with-RStudio.
However, when I run the same code as their examples, I am not getting the same outputs. For example:
library("profvis")
profvis({
data(movies, package = "ggplot2movies") # Load data
movies = movies[movies$Comedy == 1,]
plot(movies$year, movies$rating)
model = loess(rating ~ year, data = movies) # loess regression line
j = order(movies$year)
lines(movies$year[j], model$fitted[j]) # Add line to the plot
})
I should be getting an output like this:
Efficient R Output
but instead I am getting an output like this:
My output
In fact, this output isn't always consistent (for example, sometimes sources not available), but always has the "profvis" as the bottom of the flame graph, which is not the case with any examples I've seen.
I have a similar problem when running the example from the RStudio support page:
library(profvis)
profvis({
data(diamonds, package = "ggplot2")
plot(price ~ carat, data = diamonds)
m <- lm(price ~ carat, data = diamonds)
abline(m, col = "red")
})
Support Page Output
But after running the code three times in a row, here are my 3 outputs, all with the profvis in the flame graph:
Output_1
Output_2
Output_3
Also, one last note: I have fully updated R and RStudio and this did not help.
I am very confused as to why this is happening, and can't find any examples of this online. I hope I'm not missing anything obvious, and would greatly appreciate any help.
Thanks.

Creating plot using plotnine of python from R through reticulate

Being a R user, I am learning to incorporate python command in R through reticulate, I tried plotting graph using the plotnine package in R but it returned the following error, can anyone help?
library(reticulate)
library(ggplot2)
pd <- import('pandas', as='pd',convert=FALSE)
p9 <- import('plotnine')
mpg_py <- r_to_py(mpg,convert=FALSE)
mpg_pd <- pd$DataFrame(data=mpg_py)
p9$ggplot(data=mpg_pd,p9$aes(x='displ',y='cty'))
# Error in py_call_impl(callable, dots$args, dots$keywords) :
# AttributeError: 'NoneType' object has no attribute 'f_locals'
The answer to this question pointed me down a promising path for this error. It seems the error is due to an issue in the patsy package that handles the namespace/scoping for plotnine. By default the plotnine.ggplot constructor creates an environment to know where to get the plotting data and aesthetics. So adapting from the linked answer, here's a potential solution where we import the patsy package and use the environment parameter in the ggplot function to pass an evaluation environment (docs).
library(reticulate)
library(ggplot2)
pd = import('pandas',convert=F)
p9 = import('plotnine')
# new imports
patsy = import('patsy')
# import to be able to show in RStudio (see issue here: https://github.com/rstudio/rstudio/issues/4978)
matplotlib = import('matplotlib')
matplotlib$use('tkAgg')
plt = import('matplotlib.pyplot')
mpg_py <- r_to_py(mpg,convert=FALSE)
mpg_pd <- pd$DataFrame(data=mpg_py)
plot_py = p9$ggplot(mpg_pd,p9$aes(x='displ',y='cty'),
# new code (-1 was the only value that didn't throw an error)
environment = patsy$EvalEnvironment$capture(eval_env=as.integer(-1)))
print(class(plot_py)) # "plotnine.ggplot.ggplot" "python.builtin.object"
# Actually show the plot
plot_py
plt$show()

how to plot more than two plots using for loop in python?

I'm trying to do 4 plots using for loop.But I'm not sure how to do it.how can I display the plots one by one orderly?or save the figure as png?
Here is my code:
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from astropy.io import fits
import pyregion
import glob
# read in the image
xray_name = glob.glob("*.fits")
for filename in xray_name:
f_xray = fits.open(filename)
#name = file_name[:-len('.fits')]
try:
from astropy.wcs import WCS
from astropy.visualization.wcsaxes import WCSAxes
wcs = WCS(f_xray[0].header)
fig = plt.figure()
ax = plt.subplot(projection=wcs)
fig.add_axes(ax)
except ImportError:
ax = plt.subplot(111)
ax.imshow(f_xray[0].data, cmap="summer", vmin=0., vmax=0.00038, origin="lower")
reg_name=glob.glob("*.reg")
for i in reg_name:
r =pyregion.open(i).as_imagecoord(header=f_xray[0].header)
from pyregion.mpl_helper import properties_func_default
# Use custom function for patch attribute
def fixed_color(shape, saved_attrs):
attr_list, attr_dict = saved_attrs
attr_dict["color"] = "red"
kwargs = properties_func_default(shape, (attr_list, attr_dict))
return kwargs
# select region shape with tag=="Group 1"
r1 = pyregion.ShapeList([rr for rr in r if rr.attr[1].get("tag") == "Group 1"])
patch_list1, artist_list1 = r1.get_mpl_patches_texts(fixed_color)
r2 = pyregion.ShapeList([rr for rr in r if rr.attr[1].get("tag") != "Group 1"])
patch_list2, artist_list2 = r2.get_mpl_patches_texts()
for p in patch_list1 + patch_list2:
ax.add_patch(p)
#for t in artist_list1 + artist_list2:
# ax.add_artist(t)
plt.show()
the aim of the code is to plot a region on fits file image,if there is a way to change the color of the background image to white and the brighter (centeral region) as it is would be okay.Thanks
You are using colormap "summer" with provided limits. It is not clear to me what you want to achieve since the picture you posted looks more or less digital black and white pixelwise.
In matplotlib there are built in colormaps, and all of those have a reversed twin.
'summer' has a reversed twin with 'summer_r'
This can be picked up in the mpl docs at multiple spots, like colormap example, or SO answers like this.
Hope that is what you are looking for. For the future, when posting code like this, try to remove all non relevant portions as well as at minimum provide a description of the data format/type. Best is to also include a small sample of the data and it's structure. A piece of code only works together with a set of data, so only sharing one is only half the problem formulation.

Resources