Formatted String from List Psychopy - string

My task is a variation of a multiple object tracking task. There are 7 circles on the screen. It randomly selects 3 circles to change the color (red, green, blue) briefly to indicate to the participant to track these circles. After the color change, all the circles will change to the same color and the circles will move for a period of time. When the circles stop moving, a response prompt will appear, where the participant is to select one of the three colored circles ('select the red/green/blue circle'). I am having difficulty inserting which color circle to select into the formatted string. I keep getting the error message: unsupported operand type(s) for %: 'TextStim' and 'list'
I'm not sure if I need to or how to convert these lists, so any help would be much appreciated!
n_targets = 7 #seven locations
circles = [] #setting up the circle stimuli
for i in range(n_targets):
tmp = visual.Circle(win,radius = 27,units = 'pix',edges = 32,fillColor='white',lineColor = 'black',lineWidth = 1, pos=(posx[i],posy[i]))
circles.append(tmp)
cols = ['blue','red','green'] #3 colors the circles will change to
targets = random.sample(circles,3) #randomly select 3 of the 7 circles
TrialTarget = random.sample(targets, 1) #select 1 of the 3 circles to be the target for the trial
#code for movement would go here (skipping since it is not relevant)
#at end of trial, response prompt appears and ask user to select target and is where error occurs
ResponsePrompt = visual.TextStim(win, text = "Select the %s circle") %TrialTarget

In this line, you are trying to create a formatted string from a TextStim object and a Circle stimulus object rather than a string object and another string object:
ResponsePrompt = visual.TextStim(win, text = "Select the %s circle") %TrialTarget
i.e. ResponsePrompt is clearly a visual.TextStim, as you are creating it as one, and I think TrialTarget is a visual.Circle stimulus, as you randomly sample it from a list of Circles.
I'm guessing that you actually want to incorporate the colour label into the prompt text. So to fix both problems (the type incompatibility and the formatting syntax), you need to actually get one of the elements of cols, called say trialColour, and use something like this:
ResponsePrompt = visual.TextStim(win, text = "Select the %s circle" % trialColour)
i.e. here trialColour is actually a string, and the formatting operation is brought inside the brackets so it applies directly to the text string "Select the %s circle"
That should hopefully fix your immediate problem. You might also want to investigate using random.shuffle() to shuffle lists in place instead of random.sample().

Related

Visio Shape Text positioning below the shape using Text Transform

I have a building a set of stencil shapes and I need the text to display below the shape. I am using custom formulas to generate the text, and as such the volume of text changes from use case to use case.
What I have come across is using the Text Transform set of properties, and I have tried the following with success for a single line of text:
TxtWidth = TEXTWIDTH(TheText)
TxtPinX = Width * 0.5
TxtLocPinX = TxtWidth * 0.5
TxtHeight = Height * 0
TxtPinY = Height * -0.2
TxtLocPinY = TxtHieght * 0.5
TxtAngle = 0 deg
The problem arises when there is more than a single line of text to display -> the text appears 'half above (inside) and half below' the bottom the shape.
I would like to place all the text, regardless of how many lines there are, underneath the shape.
What I have tried is to set the TxtPinY = some formula different from above eg/ Height * -(TxtHeight). This seems to always result in an 'error in formula'.
I am sure that this is something simple that I am missing, but I cannot figure it out.
Can anybody point me in the right direction?
Cheers and thanks for taking a look at this,
The Frog
You could try the TEXTHEIGHT function to get around this. Specify a reasonable maximum text widht as a second parameter for it:
TxtHeight = TEXTHEIGHT(TheText,100)
TxtPinY = 0
TxtLocPinY = TxtHeight
You can use the code provided with the stencil available in this post:
http://visguy.com/vgforum/index.php?topic=7461.msg31490#msg31490

Format text of mark_text in Altair

I'm trying to create a chart somewhat along the lines of the Multi-Line Tooltip example, but I'd like to format the string that is being printed to have some text added at the end. I'm trying to modify this part:
# Draw text labels near the points, and highlight based on selection
text = line.mark_text(align='left', dx=5, dy=-5).encode(
text=alt.condition(nearest, 'y:Q', alt.value(' '))
)
Specifically, rather than 'y:Q' I want something along the lines of 'y:Q' + " suffix". I've tried doing something like this:
# Draw text labels near the points, and highlight based on selection
text = line.mark_text(align='left', dx=5, dy=-5).encode(
text=alt.condition(nearest, 'y:Q', alt.value(' '), format=".2f inches")
)
Alternatively, I've tried:
# Draw text labels near the points, and highlight based on selection
y_fld = 'y'
text = line.mark_text(align='left', dx=5, dy=-5).encode(
text=alt.condition(nearest, f"{y_fld:.2f} inches", alt.value(' '))
)
I think I see why those don't work, but I can't figure out how to intercept the value of y and pass it through a format string. Thanks!
I think the easiest way to do this is to calculate a new field using transform_calculate to compute the label that you want.
Using the example from the documentation, I would change the text chart like this:
text = line.mark_text(align='left', dx=5, dy=-5).encode(
text=alt.condition(nearest, 'label:N', alt.value(' '))
).transform_calculate(label='datum.y + " inches"')
That leads to this chart:
If you want more control, you could change the dataset with pandas beforhand. Be sure to set the type to Nominal (and not Quantitative) otherwise you would get NaNs in the tooltips.

In PyQt QTreeView item, how to set color for specific column blocks

With PyQt4 based QTreeView, I've created 2 xml tree widgets. From both the trees, want to compare selected items and highlight the difference. For e.g.,
Left String : "CompareString"
Right String : "ComPareStringRight"
The observations of the diff :
Left[0:2] is same as Right[0:2]
Left[3:3] differs with Right[3:3]
Left[4-12] is same as Right[4-12]
Right[13-17] is not present in Left
Now, want to set colors according to :
matching characters - default
Differing characters - Orange
Added characters - Green
Deleted characters - Red
How can I implement this? Unable to find any reference implementation to pick up from. Pls suggest a way forward.
class QCustomDelegate (QItemDelegate):
global showDiffPaint
def paint (self, painterQPainter, optionQStyleOptionViewItem, indexQModelIndex):
column = indexQModelIndex.column()
if showDiffPaint == 1:
QItemDelegate.paint(self, painterQPainter, optionQStyleOptionViewItem, indexQModelIndex)
else:
QItemDelegate.paint(self, painterQPainter, optionQStyleOptionViewItem, indexQModelIndex)
After digging, found it useful to convert text into html, and present as below.
However, found bugs due to " and < and > characters display. which I think I need to escape somehow...
options = QStyleOptionViewItemV4(option)
doc = QTextDocument()
doc.setHtml(txt1)
doc.setTextWidth(option.rect.width())
style = QApplication.style()
style.drawControl(QStyle.CE_ItemViewItem, options, painter)
ctx = QAbstractTextDocumentLayout.PaintContext()
textRect = style.subElementRect(QStyle.SE_ItemViewItemText,
options)
painter.translate(textRect.topLeft())
painter.setClipRect(textRect.translated(-textRect.topLeft()))
doc.documentLayout().draw(painter, ctx)

Bokeh: Control colors on Donut chart

I am using Bokeh to create a series of pie charts with bokeh.charts.Donut. The charts are based off of subsets of the same DataFrame, and all have the same category labels. I want to ensure that the same categories are displayed in the same colors across the various charts, but I haven't been able to figure out a consistent way of controlling the colors.
Currently I am sorting my input DataFrames by the label, and passing the same array of colors to the palette property of Donut. This still does not work as intended. Code is as follows:
main_colors = ['#10A400','#DB5E11','#C8C500','#CF102E','#00AFA8','#82BC00','#A40D7A','#FF7100','#1349BB']
#split out youth health problems
for_youth_health = detailed_assessment_safety.loc[detailed_assessment_safety.youth_health_prob.notnull()]
youth_health_issues = pd.DataFrame(for_youth_health.youth_health_prob.str.split(' ').tolist())
for col in youth_health_issues.columns:
newcol = 'youth_health_prob_' + str(col)
youth_health_issues = youth_health_issues.rename(columns={col:newcol})
youth_health_trans = pd.melt(youth_health_issues)
youth_health_trans = youth_health_trans.loc[youth_health_trans.value.notnull()]
youth_health_trans['issue_text'] = youth_health_trans.value.map(map_health_issues)
youth_health_trans.drop('value',axis=1,inplace=True)
youth_health_trans.sort_values(by='issue_text',ascending=True,inplace=True)
#pie of youth health issues
youth_health_issues = Donut(youth_health_trans,label='issue_text',
values='variable',agg='count',plot_width=plot_width,
plot_height=plot_height,title='Reported Youth Health Issues',
color=main_colors)
hover = HoverTool(point_policy='follow_mouse')
hover.tooltips = [('Number Reported','#values'),('Health Issue','#issue_text')]
youth_health_issues.add_tools(hover)
#split out adult health problems
for_adult_health = detailed_assessment_safety.loc[detailed_assessment_safety.adult_health_prob.notnull()]
adult_health_issues = pd.DataFrame(for_adult_health.adult_health_prob.str.split(' ').tolist())
for col in adult_health_issues.columns:
newcol = 'adult_health_prob_' + str(col)
adult_health_issues = adult_health_issues.rename(columns={col:newcol})
adult_health_trans = pd.melt(adult_health_issues)
adult_health_trans = adult_health_trans.loc[adult_health_trans.value.notnull()]
adult_health_trans['issue_text'] = adult_health_trans.value.map(map_health_issues)
adult_health_trans.drop('value',axis=1,inplace=True)
adult_health_trans.sort_values(by='issue_text',ascending=True,inplace=True)
#pie of adult health issues
adult_health_issues = Donut(adult_health_trans,label='issue_text',
values='variable',agg='count',plot_width=plot_width,
plot_height=plot_height,title='Reported Adult Health Issues',
palette=main_colors)
hover = HoverTool(point_policy='follow_mouse')
hover.tooltips = [('Number Reported','#values'),('Health Issue','#issue_text')]
adult_health_issues.add_tools(hover)
What's the proper way to map the same categories of Donut charts to colors across multiple charts? The other idea that I had was inserting a column into the DataFrame that mapped label values to colors, and then passing that column as an argument to Donut, but I couldn't make that work either. Any help is much appreciated.
After some experimentation, it turns out that when you pass an array of colors to the palette argument of Donut, the colors are associated with the donut slices based on an alphabetical sort of the slice name. So, the first color in your array of palette colors will be associated with the slice with the alphabetically first name, etc.

how to use an atomic vector as a string for a graph title in R

I'm trying to plot a graph from a matrix of z-scores in R, i would like to build a function to iterate through each column using the column header as part of the title and saving each graph as a png.I think I know how to do the iteration and saving graphs as pngs but I am getting stuck with using the vector as a string. I tried to upload the matrix with no column headers and then store matrix[1,] as a variable 'headers' to use. Then I tried to plot:
plot(1:30, rnorm(30), ylim=c(-10,10), yaxs="i", xlab = "Region", ylab = "Z-Score",main = "CNV plot of " + headers[i], type = "n")
I get:
Warning message:
In Ops.factor(left, right) : + not meaningful for factors
I try without the '+' and it says:
Error: unexpected symbol in ...
So then I looked around and found 'paste(headers[i],collapse=" ") which I though I could substitute in but it just puts the number '28' as the title.
I've tried what I thought was another potential solution:
plot(1:30, rnorm(30), ylim=c(-10,10), yaxs="i", xlab = "Region", ylab = "Z-Score",main = "Z-scores of " $headers[i], type = "n")
and I get:
Error in "Z-scores of "$headers :
$ operator is invalid for atomic vectors
I'm new to R and this seems like something that would be so simple if I happened to stumble across the right guide/tutorial after hours of google searching but I really don't have that kind of time on my hands. Any suggestions, pointers or solutions would be great??
If you want to insert values from variables into strings for a plot title, bquote is the way to go:
headers <- c(28, 14, 7) # an examle
i <- 1
plot(1:30, rnorm(30), ylim=c(-10,10), yaxs="i",
xlab = "Region", ylab = "Z-Score", type = "n",
main = bquote("CNV plot of" ~ .(headers[i])) )
Have a look at the help page of ?bquote for further information.
paste("CNV plot of", headers[i]), should work. You only need collapse if you are pasting vectors of length greater than one (headers[i] should be one length, even if header is not). R doesn't have any concatenation operators, unlike PHP, JS, etc (so +, &, . will not work, you have to use paste).
Note that your paste was paste(headers[i],collapse=" "), and if that just plotted 28, it suggests your headers vector doesn't contain what you think it does (if you didn't want 28 to be displayed, that is.
Try just looping through your vector and printing the paste command to screen to see what it displays (and also, just print the vector).

Resources