wxPython; passing a value to wx.TextCtrl from another class - oop

I'd like to thank everyone in advance for taking the time to review this question and I'm sure a lot of people get hung up on this at first and I am also a bit new to OOP, I've primarily done vbscripts in the past, so this is a new frontier to me.
My problem is that I need to:
pass a value from one panel to another...
I'm sure its something simple, but my hair is getting grey over this one.
import wx
import win32com.client
class FinanceInfo(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
zbox = wx.BoxSizer(wx.VERTICAL)
self.Description = wx.TextCtrl(self, -1, style=wx.TE_READONLY|wx.TE_MULTILINE, size=(200,204))
zbox.Add(self.Description,0, wx.EXPAND,15)
self.SetSizer(zbox)
class Frame(wx.Frame):
def __init__(self, *args, **kwargs):
super(Frame, self).__init__(*args, **kwargs)
self.InitUI()
def InitUI(self):
panel = wx.Panel(self, -1)
box1 = wx.BoxSizer(wx.HORIZONTAL)
box2 = wx.BoxSizer(wx.HORIZONTAL)
box3 = wx.BoxSizer(wx.HORIZONTAL)
box4 = wx.BoxSizer(wx.HORIZONTAL)
box5 = wx.BoxSizer(wx.HORIZONTAL)
all_box = wx.BoxSizer(wx.VERTICAL)
overall = wx.BoxSizer(wx.HORIZONTAL)
nb = wx.Notebook(panel)
page2 = FinanceInfo(nb)
nb.AddPage(page2, "Finance Information")
first = wx.StaticText(panel, label="First Name: ")
last = wx.StaticText(panel, label="Last Name: ")
self.DATA = wx.ListBox(panel, style=wx.LB_SINGLE, size=(100,100))
self.Bind(wx.EVT_LISTBOX, self.OnSelection, id=self.DATA.GetId())
self.CLYa = wx.StaticText(panel, label="")
self.P2Da = wx.StaticText(panel, label="")
self.PLYa = wx.StaticText(panel, label="")
self.FN = wx.TextCtrl(panel, size=(75,-1))
self.LN = wx.TextCtrl(panel, size=(75,-1))
Search = wx.Button(panel, label="Search Patient")
self.Bind(wx.EVT_BUTTON, self.pulldata, id=Search.GetId())
Close = wx.Button(panel, label="Close Viewer")
self.Bind(wx.EVT_BUTTON, self.OnClose, id=Close.GetId())
box1.Add(first, 0, wx.ALL, 5)
box2.Add(last, 0, wx.ALL, 5)
box1.Add(self.FN, 1, wx.ALL, 5)
box2.Add(self.LN, 1, wx.ALL, 5)
box3.Add(self.DATA, 1 , wx.ALL, 5)
box4.Add(Search, 0, wx.ALL, 5)
box5.Add(Close, 0, wx.ALL, 5)
all_box.Add(box1, 0, wx.LEFT)
all_box.Add(box2, 0, wx.LEFT)
all_box.Add(wx.StaticLine(panel), 0, wx.ALL|wx.EXPAND, 5)
all_box.Add(box3, 0, wx.CENTER)
all_box.Add(box4, 0, wx.CENTER)
all_box.Add(box5, 0, wx.CENTER)
overall.Add(all_box,0,wx.EXPAND)
overall.Add(nb, 1, wx.EXPAND)
panel.SetSizer(overall)
self.SetSize((500, 275))
self.SetTitle("Maxident Historical Data Viewer")
self.Centre()
self.Show(True)
def OnClose(self, event):
quit()
def pulldata(self, event):
firstname = str(self.FN.GetValue())
lastname = str(self.LN.GetValue())
access = pullID(lastname.strip(), firstname.strip())
access.MoveFirst
dat = ""
while not access.EOF:
a = str(access.Fields("First Name").value)
b = str(access.Fields("Last Name").value)
PID = str(access.Fields("Patient Number").value)
name = str(a + " " + b + " :" + PID)
self.DATA.Insert(name, 0)
access.MoveNext()
def OnSelection(self, event):
x = str(self.DATA.GetStringSelection())
y = x.split(":")
PID = y[1]
pullfinancedata(PID)
def pullID(lastname, firstname):
DB = r"C:\Converted DBases\DATA.mdb"
engine = win32com.client.Dispatch("DAO.DBEngine.36")
db = engine.OpenDatabase(DB)
sql = "select [Patient Number], [First Name], [Last Name] from [tPatients] where [Last Name]='" + lastname.upper() + "' and [First Name]='" + firstname.upper() + "'"
access = db.OpenRecordset(sql)
return access
def pullfinancedata(PID):
DB = r"C:\Converted DBases\DATA.mdb"
engine = win32com.client.Dispatch("DAO.DBEngine.36")
db = engine.OpenDatabase(DB)
sql = "select * from [tPayment History] where [Patient Number]=" + PID
access = db.OpenRecordset(sql)
dat = ""
while not access.EOF:
PD = "Payment Date:\t" + str(access.Fields("Payment Date").value) + '\n'
PM = "Payment Method:\t" + str(access.Fields("Payment Method").value) + '\n'
PP = "Patient Payment:\t" + str(access.Fields("Patient Payment").value) + '\n'
IP = "Insurance Payment:\t" + str(access.Fields("Insurance Payment").value) + '\n'
dat = dat + PD + PM + PP + IP + "\n ------------------ \n"
access.MoveNext()
"""
THIS IS WHERE I NEED HELP!
"""
print dat
"""
I need this dat variable to be passed to the FinanceInfo class and
i've tried FinanceInfo.Description.SetValue(dat) but its not working
"""
def main():
ex = wx.App()
Frame(None)
ex.MainLoop()
if __name__ == '__main__':
main()
I would also be grateful for any other tips or tricks. Not sure if my BoxSizer's make any sense, I mostly got the examples around other places.

There are several ways to do this:
Keep a reference to each panel and pass them around willy nilly. Then you can do stuff like self.panelOne.MyTextCtrl.SetValue(self.otherText.GetValue())
Use wx.PostEvent to pass around the information
Use pubsub
There are probably other ways too, but I prefer the last one for this sort of thing. You can read a simple example here: http://www.blog.pythonlibrary.org/2010/06/27/wxpython-and-pubsub-a-simple-tutorial/

The answer from Mike is correct. For simple communication between a few classes I however prefer to just send a reference to the other class. It is a clean/transparent method that doesnt needs any additional library. See here an example

I hope you already solved ... but if not I revised your example using pubsub and adodbapi.
I used my mdb and adodbapi becouse logic using OpendDataBase and .movenext not works in my Python 2.7 installation .
enter code here
import wx
from wx.lib.pubsub import Publisher
import win32com.client
import adodbapi
adodbapi.adodbapi.verbose = True
# adds details to the sample printout
class FinanceInfo(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
Publisher().subscribe(self.showFrame, ("show.mainframe"))
zbox = wx.BoxSizer(wx.VERTICAL)
self.Description = wx.TextCtrl(self, -1, style=wx.TE_READONLY|wx.TE_MULTILINE, size=(200,204))
zbox.Add(self.Description,0, wx.EXPAND,15)
self.SetSizer(zbox)
def showFrame(self, msg):
"""
Shows the frame and shows the message sent in the
text control
"""
self.Description.SetValue(msg.data)
class Frame(wx.Frame):
def __init__(self, *args, **kwargs):
super(Frame, self).__init__(*args, **kwargs)
self.InitUI()
def InitUI(self):
#self.FinancePanelInfo = FinanceInfo(self)
panel = wx.Panel(self, -1)
box1 = wx.BoxSizer(wx.HORIZONTAL)
box2 = wx.BoxSizer(wx.HORIZONTAL)
box3 = wx.BoxSizer(wx.HORIZONTAL)
box4 = wx.BoxSizer(wx.HORIZONTAL)
box5 = wx.BoxSizer(wx.HORIZONTAL)
all_box = wx.BoxSizer(wx.VERTICAL)
overall = wx.BoxSizer(wx.HORIZONTAL)
nb = wx.Notebook(panel)
page2 = FinanceInfo(nb)
nb.AddPage(page2, "Finance Information")
first = wx.StaticText(panel, label="First Name: ")
last = wx.StaticText(panel, label="Last Name: ")
self.DATA = wx.ListBox(panel, style=wx.LB_SINGLE, size=(100,100))
self.Bind(wx.EVT_LISTBOX, self.OnSelection, id=self.DATA.GetId())
self.CLYa = wx.StaticText(panel, label="")
self.P2Da = wx.StaticText(panel, label="")
self.PLYa = wx.StaticText(panel, label="")
self.FN = wx.TextCtrl(panel, size=(75,-1))
self.LN = wx.TextCtrl(panel, size=(75,-1))
Search = wx.Button(panel, label="Search Patient")
self.Bind(wx.EVT_BUTTON, self.pulldata, id=Search.GetId())
Close = wx.Button(panel, label="Close Viewer")
self.Bind(wx.EVT_BUTTON, self.OnClose, id=Close.GetId())
box1.Add(first, 0, wx.ALL, 5)
box2.Add(last, 0, wx.ALL, 5)
box1.Add(self.FN, 1, wx.ALL, 5)
box2.Add(self.LN, 1, wx.ALL, 5)
box3.Add(self.DATA, 1 , wx.ALL, 5)
box4.Add(Search, 0, wx.ALL, 5)
box5.Add(Close, 0, wx.ALL, 5)
all_box.Add(box1, 0, wx.LEFT)
all_box.Add(box2, 0, wx.LEFT)
all_box.Add(wx.StaticLine(panel), 0, wx.ALL|wx.EXPAND, 5)
all_box.Add(box3, 0, wx.CENTER)
all_box.Add(box4, 0, wx.CENTER)
all_box.Add(box5, 0, wx.CENTER)
overall.Add(all_box,0,wx.EXPAND)
overall.Add(nb, 1, wx.EXPAND)
panel.SetSizer(overall)
self.SetSize((500, 275))
self.SetTitle("Maxident Historical Data Viewer")
self.Centre()
self.Show(True)
def OnClose(self, event):
quit()
def pulldata(self, event):
firstname = str(self.FN.GetValue())
lastname = str(self.LN.GetValue())
access = pullID(firstname.strip(), lastname.strip())
dat = ""
for rec in access:
a = str(rec[0])
b = str(rec[1])
#PID = str(access.Fields("Patient Number").value)
name = str(a + ":" + b)
print name
self.DATA.Insert(name, 0)
#access.MoveNext()
access.close
def OnSelection(self, event):
x = str(self.DATA.GetStringSelection())
y = x.split(":")
PID = y[0]
#PID = "Rossini Gianni"
dati = pullfinancedata(PID)
righe =""
for line in dati:
print line
riga = str(line)
righe = righe + riga + "\n"
Publisher().sendMessage(("show.mainframe"), righe)
def pullID(name, firstname):
#name = "ROSSINI GIANNI"
#DB = r"d:\coop&mie_doc\pdci\iscritti_2007.mdb"
# db = engine.OpenDatabase(DB)
# data_source = "D:\coop&mie_doc\pdci\iscritti_2007.mdb"
# mdw ="C:\Programmi\File comuni\System\System.mdw"
# DSN = "PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=%s;Jet OLEDB:System Database=%s;" % (data_source, mdw)
SQL_statement = "select [name], [address] from [tessere_2008] where [name] LIKE '" + name.upper() + "%'"
#SQL_statement = "select [name], [address] from [tessere_2008] "
#access = db.OpenRecordset(sql)
# access = engine.Open(sql,conAccess,1,3)
_databasename = "d:\coop&mie_doc\pdci\iscritti_2007.mdb"
_table_name= 'tessere_2008'
_username = ''
_password = ''
_mdw = "C:\Programmi\File comuni\System\System.mdw"
constr = 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source=%s;User Id=%s;Password=%s;Jet OLEDB:System Database=%s;' % (_databasename, _username, _password, _mdw)
#constr = 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source=%s;Jet OLEDB:System Database=%s;' % (_databasename, _mdw)
conAccess = adodbapi.connect(constr)
accessdb = conAccess.cursor()
# accessdb = msaccess.AccessDb()
# connAccess = accessdb.connect("D:\coop&mie_doc\pdci\iscritti_2007.mdb", "Yram", "","C:\Programmi\File comuni\System\System.mdw")
print SQL_statement
accessdb.execute(SQL_statement)
print 'result rowcount shows as= %d. (Note: -1 means "not known")' \
% (accessdb.rowcount,)
# fields = access.getFields()
# print fields
# for item in access:
# print item
#get the results
access = accessdb.fetchmany(1)
#print them
for rec in access:
print rec
return accessdb
def pullfinancedata(PID):
print "pullfinancedata"
print PID
#DB = r"d:\coop&mie_doc\pdci\iscritti_2007.mdb"
#engine = win32com.client.Dispatch(r'ADODB.Recordset')
#db = engine.OpenDatabase(DB)
_databasename = "d:\coop&mie_doc\pdci\iscritti_2007.mdb"
_table_name= 'tessere_2008'
_username = ''
_password = ''
_mdw = "C:\Programmi\File comuni\System\System.mdw"
constr = 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source=%s;User Id=%s;Password=%s;Jet OLEDB:System Database=%s;' % (_databasename, _username, _password, _mdw)
#constr = 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source=%s;Jet OLEDB:System Database=%s;' % (_databasename, _mdw)
conAccess = adodbapi.connect(constr)
accessdb = conAccess.cursor()
#SQL_statement = "select [name], [address] from [tessere_2008] where [name] LIKE '" + name.upper() + "%'"
SQL_statement = "select * from [Tesseramento] where [anagra_iscritto]='" + PID + "'"
#access = db.OpenRecordset(sql)
print SQL_statement
accessdb.execute(SQL_statement)
print 'result rowcount shows as= %d. (Note: -1 means "not known")' \
% (accessdb.rowcount,)
dat = ""
#while not access.EOF:
# PD = "Payment Date:\t" + str(access.Fields("Payment Date").value) + '\n'
# PM = "Payment Method:\t" + str(access.Fields("Payment Method").value) + '\n'
# PP = "Patient Payment:\t" + str(access.Fields("Patient Payment").value) + '\n'
# IP = "Insurance Payment:\t" + str(access.Fields("Insurance Payment").value) + '\n'
# dat = dat + PD + PM + PP + IP + "\n ------------------ \n"
# access.MoveNext()
"""
THIS IS WHERE I NEED HELP!
"""
#get the results
access = accessdb.fetchmany(accessdb.rowcount)
#print them
#for rec in access:
# print rec
"""
I need this dat variable to be passed to the FinanceInfo class and
i've tried FinanceInfo.Description.SetValue(dat) but its not working
"""
return access
def main():
ex = wx.App()
Frame(None)
ex.MainLoop()
if __name__ == '__main__':
main()

Related

Automatically assigning p-value position in ggplot loop

I am running an mapply loop on a huge set of data to graph 13 parameters for 19 groups. This is working great except the p-value position. Due to the data varying for each plot I cannot assign position using label.y = 125 for example, in some plots it is in the middle of the bar/error bar. However, I can't assign it higher without having it way to high on other graphs. Is there a way to adjust to the data and error bars?
This is my graphing function and like I said the graph is great, except p-value position. Specifically, the stat compare means anova line.
ANOVA_plotter <- function(Variable, treatment, Grouping, df){
Inputdf <- df %>%
filter(Media == treatment, Group == Grouping) %>%
ggplot(aes_(x = ~ID, y = as.name(Variable))) +
geom_bar(aes(fill = ANOVA_Status), stat = "summary", fun = "mean", width = 0.9) +
stat_summary(geom = "errorbar", fun.data = "mean_sdl", fun.args = list(mult = 1), size = 1) +
labs(title = paste(Variable, "in", treatment, "in Group", Grouping, sep = " ")) +
theme(legend.position = "none",axis.title.x=element_blank(), axis.text = element_text(face="bold", size = 18 ), axis.text.x = element_text(angle = 45, hjust = 1)) +
stat_summary(geom = "errorbar", fun.data = "mean_sdl", fun.args = list(mult = 1), width = 0.2) +
stat_compare_means(method = "anova", label.y = 125) +
stat_compare_means(label = "p.signif", method = "t.test", paired = FALSE, ref.group = "Control")
}
I get graphs that look like this
(https://i.stack.imgur.com/hV9Ad.jpg)
But I can't assign it to label.y = 200 because of plots like this
(https://i.stack.imgur.com/uStez.jpg)

Strange Issues with ggplot?

PLEASE HELP, something seems not to be working here,I previously ploted this figure and it was working fine, however, now it seems something is off.
The categories are no longer orderly and some of them appear twice...
...
ggplot(data = data_c, aes(x = reorder(Sektor, -Preis), y = Preis)) +
geom_bar(stat = "identity", width = data_c$Menge/26) +
geom_line(data = data_c, aes(group = 1, x = Sektor,
y = Preis, colour = "40 € pro MWh")) +
geom_line(data = data_d, aes(group = 1, x = sektoren2,
y = preise2, colour = "60 € pro MWh")) +
geom_label(aes(label = preise2a), nudge_y = 30, size = 4) +
geom_label(aes(label = twh2), nudge_y = 6, size = 4) +
geom_text(aes(label = euros), vjust = 1.5, colour = "white", size = 2) +
scale_y_continuous(labels = dollar_format(suffix = " €", prefix = "")) +
labs(title = "Merrit Order Curve Wasserstoff",
subtitle = "Mengen in TWh und Preise in Euro pro MWh",
x = "Sektoren",
y = "Preise in Euro pro MWh") +
theme_bw()
´´´

Passing python list in hive query as parameters

from tkinter import *
import pyodbc
with pyodbc.connect("DSN=ffff", autocommit=True) as conn:
df2 = pd.read_sql("SELECT * FROM holdingsummarysaaas", conn)
list46 = []
for md in df2['clientcode']:
list46.append(md)
print(list46)
result = []
for i in list46:
if i not in result:
result.append(i)
print(result)
#list_no_nan = [x for x in result if pd.notnull(x)]
#print(list_no_nan)
#select name from studens where id in (%s)" % ",".join(map(str,mylist)
#def fun():
num1 = Entry(root)
blank = Entry(root)
Ans = (num1.get())
blank.insert(0, Ans)
if Ans in result:
df2 = pd.read_sql('SELECT * FROM holdingsummary where ' + ' or '.join(('clientcode = '
+ str(n) for n in result)),conn)
#df2 = pd.read_sql("SELECT * FROM holdingsummary where clientcode = '" + Ans + "'",
conn)
print(df2)
I am taking unique clientcodes from database and I want user input which is in fun
function should access the results list(unique clientcode )check each clientcode from list
and check whether entered clientcode if same in result list then open that clientcode.
for eg:
Ans=='100014'
#df2 = pd.read_sql("SELECT * FROM holdingsummarysaaas where clientcode = '100014', conn)

when i try to run the program, at the end its gives an error saying 'unexpected eof while parsing' how can i fix?

def main():
randOperation = Randomchoice(operation)
while True:
try:
randOperation()
randOperation = choice(operation)
userAns=int(input("Answer: "))
if userAns == answers:
print("Correct!" + "\n")
score = score + 1
NumOfTries =NumOfTries + 1
else:
print("Incorrect!" + "\n")
NumOfTries = NumOfTries + 1 #here is where the issue is

Create a ggplot2 survival curve with censored table

I am trying to create a Kaplan-Meier plot with 95% confidence bands plus having the censored data in a table beneath it. I can create the plot, but not the table. I get the error message: Error in grid.draw(both) : object 'both' not found.
library(survival)
library(ggplot2)
library(GGally)
library(gtable)
data(lung)
sf.sex <- survfit(Surv(time, status) ~ sex, data = lung)
pl.sex <- ggsurv(sf.sex) +
geom_ribbon(aes(ymin=low,ymax=up,fill=group),alpha=0.3) +
guides(fill=guide_legend("sex"))
pl.sex
tbl <- ggplot(df_nums, aes(x = Time, y = factor(variable), colour = variable,+
label=value)) +
geom_text() +
theme_bw() +
theme(panel.grid.major = element_blank(),+
legend.position = "none",+
plot.background = element_blank(), +
panel.grid.major = element_blank(),+
panel.grid.minor = element_blank(),+
panel.border = element_blank(),+
legend.position="none",+
axis.line = element_blank(),+
axis.text.x = element_blank(),+
axis.text.y = element_text(size=15, face="bold", color = 'black'),+
axis.ticks=element_blank(),+
axis.title.x = element_blank(),+
axis.title.y = element_blank(),+
plot.title = element_blank()) +
scale_y_discrete(breaks=c("Group.A", "Group.B"), labels=c("Group A", "Group B"))
both = rbind(ggplotGrob(g), ggplotGrob(tbl), size="last")
panels <- both$layout$t[grep("panel", both$layout$name)]
both$heights[panels] <- list(unit(1,"null"), unit(2, "lines"))
both <- gtable_add_rows(both, heights = unit(1,"line"), 8)
both <- gtable_add_grob(both, textGrob("Number at risk", hjust=0, x=0), t=9, l=2, r=4)
grid.newpage()
grid.draw(both)
I solved the problem by using the Rcmdrplugin KMggplot2 The code is generated by the plugin after selecting the data and variables.
library(survival, pos=18)
data(lung, package="survival")
lung <- within(lung, {
sex <- factor(sex, labels=c('male','female'))
})
ggthemes_data <- ggthemes::ggthemes_data
require("ggplot2")
.df <- na.omit(data.frame(x = lung$time, y = lung$status, z = lung$sex))
.df <- .df[do.call(order, .df[, c("z", "x"), drop = FALSE]), , drop = FALSE]
.fit <- survival::survfit(survival::Surv(time = x, event = y, type = "right") ~ z,
.df)
.pval <- plyr::ddply(.df, plyr::.(),
function(x) {
data.frame(
x = 0, y = 0, df = 1,
chisq = survival::survdiff(
survival::Surv(time = x, event = y, type = "right") ~ z, x
)$chisq
)})
.pval$label <- paste0(
"paste(italic(p), \" = ",
signif(1 - pchisq(.pval$chisq, .pval$df), 3),
"\")"
)
.fit <- data.frame(x = .fit$time, y = .fit$surv, nrisk = .fit$n.risk, nevent =
.fit$n.event, ncensor= .fit$n.censor, upper = .fit$upper, lower = .fit$lower)
.df <- .df[!duplicated(.df[,c("x", "z")]), ]
.df <- .fit <- data.frame(.fit, .df[, c("z"), drop = FALSE])
.med <- plyr::ddply(.fit, plyr::.(z), function(x) {
data.frame(
median = min(subset(x, y < (0.5 + .Machine$double.eps^0.5))$x)
)})
.df <- .fit <- rbind(unique(data.frame(x = 0, y = 1, nrisk = NA, nevent = NA,
ncensor = NA, upper = 1, lower = 1, .df[, c("z"), drop = FALSE])), .fit)
.cens <- subset(.fit, ncensor == 1)
.tmp1 <- data.frame(as.table(by(.df, .df[, c("z"), drop = FALSE], function(d)
max(d$nrisk, na.rm = TRUE))))
.tmp1$x <- 0
.nrisk <- .tmp1
for (i in 1:9) {.df <- subset(.fit, x < 100 * i); .tmp2 <-
data.frame(as.table(by(.df, .df[, c("z"), drop = FALSE], function(d) if
(all(is.na(d$nrisk))) NA else min(d$nrisk - d$nevent - d$ncensor, na.rm = TRUE))));
.tmp2$x <- 100 * i; .tmp2$Freq[is.na(.tmp2$Freq)] <- .tmp1$Freq[is.na(.tmp2$Freq)];
.tmp1 <- .tmp2; .nrisk <- rbind(.nrisk, .tmp2)}
.nrisk$y <- rep(seq(0.075, 0.025, -0.05), 10)
.plot <- ggplot(data = .fit, aes(x = x, y = y, colour = z)) +
RcmdrPlugin.KMggplot2::geom_stepribbon(data = .fit, aes(x = x, ymin = lower, ymax =
upper, fill = z), alpha = 0.25, colour = "transparent", show.legend = FALSE, kmplot
= TRUE) + geom_step(size = 1.5) +
geom_linerange(data = .cens, aes(x = x, ymin = y,
ymax = y + 0.02), size = 1.5) +
geom_text(data = .pval, aes(y = y, x = x, label =
label), colour = "black", hjust = 0, vjust = -0.5, parse = TRUE, show.legend =
FALSE, size = 14 * 0.282, family = "sans") +
geom_vline(data = .med, aes(xintercept
= median), colour = "black", lty = 2) + scale_x_continuous(breaks = seq(0, 900, by
= 100), limits = c(0, 900)) +
scale_y_continuous(limits = c(0, 1), expand = c(0.01,0)) + scale_colour_brewer(palette = "Set1") + scale_fill_brewer(palette = "Set1") +
xlab("Time from entry") + ylab("Proportion of survival") + labs(colour = "sex") +
ggthemes::theme_calc(base_size = 14, base_family = "sans") + theme(legend.position
= c(1, 1), legend.justification = c(1, 1))
.nrisk$y <- ((.nrisk$y - 0.025) / (max(.nrisk$y) - 0.025) + 0.5) * 0.5
.plot2 <- ggplot(data = .nrisk, aes(x = x, y = y, label = Freq, colour = z)) +
geom_text(size = 14 * 0.282, family = "sans") + scale_x_continuous(breaks = seq(0,900, by = 100), limits = c(0, 900)) +
scale_y_continuous(limits = c(0, 1)) +
scale_colour_brewer(palette = "Set1") + ylab("Proportion of survival") +
RcmdrPlugin.KMggplot2::theme_natrisk(ggthemes::theme_calc, 14, "sans")
.plot3 <- ggplot(data = subset(.nrisk, x == 0), aes(x = x, y = y, label = z, colour = z)) +
geom_text(hjust = 0, size = 14 * 0.282, family = "sans") +
scale_x_continuous(limits = c(-5, 5)) + scale_y_continuous(limits = c(0, 1)) +
scale_colour_brewer(palette = "Set1") +
RcmdrPlugin.KMggplot2::theme_natrisk21(ggthemes::theme_calc, 14, "sans")
.plotb <- ggplot(.df, aes(x = x, y = y)) + geom_blank() +
RcmdrPlugin.KMggplot2::theme_natriskbg(ggthemes::theme_calc, 14, "sans")
grid::grid.newpage(); grid::pushViewport(grid::viewport(layout =
grid::grid.layout(2, 2, heights = unit(c(1, 3), c("null", "lines")), widths =
unit(c(4, 1), c("lines", "null")))));
print(.plotb, vp =
grid::viewport(layout.pos.row = 1:2, layout.pos.col = 1:2));
print(.plot , vp =
grid::viewport(layout.pos.row = 1 , layout.pos.col = 1:2));
print(.plot2, vp =
grid::viewport(layout.pos.row = 2 , layout.pos.col = 1:2));
print(.plot3, vp =
grid::viewport(layout.pos.row = 2 , layout.pos.col = 1 ));
.plot <- recordPlot()
print(.plot)
Here's a start (code below)
I guess you can create the table need and replace it by the random.table
# install.packages("ggplot2", dependencies = TRUE)
# install.packages("RGraphics", dependencies = TRUE)
# install.packages("gridExtra", dependencies = TRUE)
# install.packages("survival", dependencies = TRUE)
require(ggplot2)
library(RGraphics)
library(gridExtra)
library(survival)
# Plot
data(lung)
sf.sex <- survfit(Surv(time, status) ~ sex, data = lung)
pl.sex <- ggsurv(sf.sex) +
geom_ribbon(aes(ymin=low,ymax=up,fill=group),alpha=0.3) +
guides(fill=guide_legend("sex"))
# Table
random.table <- data.frame("CL 95"=rnorm(5),n=runif(5,1,3))
pl.table <- tableGrob(random.table)
# Arrange the plots on the same page
grid.arrange(pl.sex, pl.table, ncol=1)