在MATLAB中更改seqlogo图形的x轴

6
我正在使用编程方式制作大量序列标志图。它们有数百列宽,因此正常情况下运行seqlogo会创建太细的字母难以看清。我注意到我只关心其中的一些列(不一定是连续的列)…大多数是噪音,但有些高度保守。
我使用类似于这样的片段:
wide_seqs = cell2mat(arrayfun(@randseq, repmat(200, [500 1]), 'uniformoutput', false));
wide_seqs(:, [17,30, 55,70,130]) = repmat(['ATCGG'], [500 1])

conserve_cell = seqlogo(wide_seqs, 'displaylogo', false);
high_bit_cols = any(conserve_cell{2}>1.0,1);
[~, handle] = seqlogo(wide_seqs(:,high_bit_cols ));

尽管我这样做会失去数据来自哪些列的信息。

通常我会改变 seqlogo 的 x 轴。然而,seqlogo 是一种疯狂的基于 Java 的对象,调用如下:

set(handle, 'xticklabel', num2str(find(high_bit_cols)))

不起作用。非常感谢您的帮助。

谢谢, 威尔

编辑:

对于赏金,我愿意接受任何一种疯狂的方法来更改轴标签,包括(但不限于):使用图像处理工具箱在保存后修改图像,使用文本框创建新的seqlogo函数,修改Java代码(如果可能),等等。我不愿意接受诸如“使用Python”,“使用此R库”或任何其他非Matlab解决方案之类的东西。


我借鉴了@gnoice和@yuk的答案。我使用了yuk的“字母生成”部分来生成图像片段……因为有时我会用AA,有时会用NT,所以能够即兴生成很重要。然而,我不是将它们写入文件,而是将图像保存在一个单元格中。然后,我使用gnovice的方法将图像文件写入一个巨大的图像矩阵中……尽管我使用IMRESIZE来调整图像大小。我的最终答案几乎有50%的代码来自每个人加上一些参数解析和检查。我不确定如何授予“声望”,你们两个有什么想法吗? - JudoWill
如果你无法选择一个,我想你可以让社区在几天内投票选出最高票的答案。你可以将你的综合解决方案发布为答案以完整性为考虑,但你不能为此颁发赏金给自己(http://meta.stackexchange.com/questions/18841/lost-reputation-after-answering-my-own-question-with-bounty)。 - gnovice
@gnovice:这是我的计划(既包括奖励,也包括完整性)...我还在创建一个更“通用”的解决方案,并将其放在Mathworks FileExchange上...我会确保引用这篇帖子 :) - JudoWill
1
仅供参考,Mathworks支持团队刚刚回复了我的请求(在我发帖当天发送)。他们的答复是:“目前不支持,并且没有解决方法。我已将此转发给开发团队,作为未来版本可能添加的功能。”我很高兴StackOverflow成员有更多的创造力 :) - JudoWill
1
MathWorks的支持质量有所波动。有时他们会轻易地说“无法修复-转发给其他人”,但有时他们确实会付出很多努力为您带来解决方案。话虽如此,我从未见过任何支持人员像gnovice或yuk一样展现出如此多的创造力和韧性。 - Jonas
显示剩余2条评论
5个回答

5

好的,我花了几个小时解决了这个问题。看起来你不能将任何MATLAB对象(轴或文本框)放在那个hgjavacomponent对象的顶部。当然,我不能修改Java代码。因此,我找到的唯一可行的解决方案是从头开始创建图形。

我不想重新编写计算权重矩阵(符号高度)的代码,你已经完成了这个工作。但是如果你不想使用MATLAB的seqlogo,也可以这样做。因此,我稍微改变了你的最后一行代码以获取矩阵:

[wm, handle] = seqlogo(wide_seqs(:,high_bit_cols ));

文本符号的问题在于您无法精确地控制它们的大小,也无法将符号适应文本框。这可能是MATLAB决定使用Java图形对象的原因。但是我们可以创建符号图像并处理它们。

以下是创建字母图像的代码:

letters = wm{1};
clr = [0 1 0; 0 0 1; 1 0.8 0;1 0 0]; % corresponding colors
for t = 1:numel(letters)
    hf = figure('position',[200 200 100 110],'color','w');
    ha = axes('parent',hf, 'visible','off','position',[0 0 1 1]);
    ht = text(50,55,letters(t),'color',clr(t,:),'units','pixels',...
        'fontsize',100,'fontweight','norm',...
        'vertical','mid','horizontal','center');
    F = getframe(hf); % rasterize the letter
    img = F.cdata;
    m = any(img < 255,3); % convert to binary image
    m(any(m,2),any(m,1))=1; % mask to cut white borders
    imwrite(reshape(img(repmat(m,[1 1 3])),[sum(any(m,2)) sum(any(m,1)) 3]),...
        [letters(t) '.png'])
    close(hf)
end

然后我们使用这些图像来绘制新的序列标志图:

xlabels = cellstr(num2str(find(high_bit_cols)'));
letters = wm{1};
wmat=wm{2}; % weight matrix from seqlogo
[nletters  npos] = size(wmat);
wmat(wmat<0) = 0; % cut negative values

% prepare the figure
clf
hAx = axes('parent',gcf,'visible','on');
set(hAx,'XLim',[0.5 npos+0.5],'XTick',1:npos,'XTickLabel',xlabels)
ymax = ceil(max(sum(wmat)));
ylim([0 ymax])
axpos = get(hAx,'Position');
step = axpos(3)/npos;

% place images of letters
for i=1:npos
    [wms idx] = sort(wmat(:,i)); % largest on the top
    let_show = letters(idx);
    ybot = axpos(2);
    for s=1:nletters
        if wms(s)==0, continue, end;
        axes('position',[axpos(1) ybot step wms(s)/ymax*axpos(4)])
        ybot = ybot + wms(s)/ymax*axpos(4);
        img = imread([let_show(s) '.png']);
        image(img)
        set(gca,'visible','off')
    end
    axpos(1)=axpos(1)+step;
end

这是结果: alt text http://img716.imageshack.us/img716/2073/seqlogoexample.png 当然,代码和图像可以进一步改进,但我希望这是您可以开始使用的内容。如果我漏掉了什么,请告诉我。

看起来很不错...我正在尝试使用文本框的方法,但遇到了一些问题,我相信你也注意到了,无法让一个字母占据整个框。我会再试几分钟以确保它能正常工作...我可能会尝试去掉临时写字母的部分,但那只是个人喜好。干得好! - JudoWill
将文本制作成图像,然后放置它们:太棒了。+1 我几乎很抱歉,我更喜欢gnovices的方法。 - Jonas

4
我在尝试修改yuk didSEQLOGO得到的图形时,遇到了同样的问题,因此这里是我自己尝试模仿它外观的版本。它是一个函数seqlogo_new.m,你需要提供两个参数:你的序列和一个可选的最小位值。它需要一个图像文件ACGT.jpg,可以在此链接找到。
下面是该函数的代码:
function hFigure = seqlogo_new(S,minBits)
%# SEQLOGO_NEW   Displays sequence logos for DNA.
%#   HFIGURE = SEQLOGO_NEW(SEQS,MINBITS) displays the
%#   sequence logo for a set of aligned sequences SEQS,
%#   showing only those columns containing at least one
%#   nucleotide with a minimum bit value MINBITS. The
%#   MINBITS parameter is optional. SEQLOGO_NEW returns
%#   a handle to the rendered figure HFIGURE.
%#
%#   SEQLOGO_NEW calls SEQLOGO to perform some of the
%#   computations, so to use this function you will need
%#   access to the Bioinformatics Toolbox.
%#
%#   See also seqlogo.

%# Author: Ken Eaton
%# Version: MATLAB R2009a
%# Last modified: 3/30/10
%#---------------------------------------------------------

  %# Get the weight matrix from SEQLOGO:

  W = seqlogo(S,'DisplayLogo',false);
  bitValues = W{2};

  %# Select columns with a minimum bit value:

  if nargin > 1
    highBitCols = any(bitValues > minBits,1);  %# Plot only high-bit columns
    bitValues = bitValues(:,highBitCols);
  else
    highBitCols = true(1,size(bitValues,2));   %# Plot all columns
  end

  %# Sort the bit value data:

  [bitValues,charIndex] = sort(bitValues,'descend');  %# Sort the columns
  nSequence = size(bitValues,2);                      %# Number of sequences
  maxBits = ceil(max(bitValues(:)));                  %# Upper plot limit

  %# Break 4-letter image into a 1-by-4 cell array of images:

  imgACGT = imread('ACGT.jpg');                %# Image of 4 letters
  [nRows,nCols,nPages] = size(imgACGT);        %# Raw image size
  letterIndex = round(linspace(1,nCols+1,5));  %# Indices of letter tile edges
  letterImages = {imgACGT(:,letterIndex(1):letterIndex(2)-1,:), ...
                  imgACGT(:,letterIndex(2):letterIndex(3)-1,:), ...
                  imgACGT(:,letterIndex(3):letterIndex(4)-1,:), ...
                  imgACGT(:,letterIndex(4):letterIndex(5)-1,:)};

  %# Create the image texture map:

  blankImage = repmat(uint8(255),[nRows round(nCols/4) 3]);  %# White image
  fullImage = repmat({blankImage},4,2*nSequence-1);  %# Cell array of images
  fullImage(:,1:2:end) = letterImages(charIndex);    %# Add letter images
  fullImage = cat(1,cat(2,fullImage{1,:}),...        %# Collapse cell array
                    cat(2,fullImage{2,:}),...        %#   to one 3-D image
                    cat(2,fullImage{3,:}),...
                    cat(2,fullImage{4,:}));

  %# Initialize coordinates for the texture-mapped surface:

  X = [(1:nSequence)-0.375; (1:nSequence)+0.375];
  X = repmat(X(:)',5,1);     %'# Surface x coordinates
  Y = [zeros(1,nSequence); cumsum(flipud(bitValues))];
  Y = kron(flipud(Y),[1 1]);  %# Surface y coordinates
  Z = zeros(5,2*nSequence);   %# Surface z coordinates

  %# Render the figure:

  figureSize = [602 402];                   %# Figure size
  screenSize = get(0,'ScreenSize');         %# Screen size
  offset = (screenSize(3:4)-figureSize)/2;  %# Offset to center figure
  hFigure = figure('Units','pixels',...
                   'Position',[offset figureSize],...
                   'Color',[1 1 1],...
                   'Name','Sequence Logo',...
                   'NumberTitle','off');
  axes('Parent',hFigure,...
       'Units','pixels',...
       'Position',[60 100 450 245],...
       'FontWeight','bold',...
       'LineWidth',3,...
       'TickDir','out',...
       'XLim',[0.5 nSequence+0.5],...
       'XTick',1:nSequence,...
       'XTickLabel',num2str(find(highBitCols)'),...  %'
       'YLim',[-0.03 maxBits],...
       'YTick',0:maxBits);
  xlabel('Sequence Position');
  ylabel('Bits');
  surface(X,Y,Z,fullImage,...
          'FaceColor','texturemap',...
          'EdgeColor','none');
  view(2);

end

这里是它使用的几个例子:

S = ['ATTATAGCAAACTA'; ...  %# Sample data
     'AACATGCCAAAGTA'; ...
     'ATCATGCAAAAGGA'];
seqlogo_new(S);             %# A normal plot similar to SEQLOGO

alt text

seqlogo_new(S,1);        %# Plot only columns with bits > 1

alt text


这个答案的好处在于你可以将其用作“普通”图形...你可以将其用作子图或放入任意坐标轴对象中。而使用yuk的答案,由于他手动放置坐标轴对象,因此无法调整大小。 - JudoWill
@JudoWill:我采用了一种非传统的方法,将所有显示的字母都制作成一个大图像,并将其纹理映射到表面上,以根据需要拉伸它们。这使我只有1组轴,但代码可能有点难以理解。 ;)另一种方法(介于yuk的答案和我的答案之间)是在一个坐标轴集中绘制每个字母作为自己的图像对象,这可能比我上面做的更具图形效率。 - gnovice
我喜欢这个比yuk的更多。+1 - Jonas

3
所以我创建了另一种解决方案,同时采用了yuk和gnovice的方法。当我试着使用这个解决方案时,我意识到我真的很想能够将输出用作"子图",并且可以任意更改字母的颜色。
由于yuk使用编程方式放置的带有嵌入式字母的轴对象,如果要修改他的代码以绘制到任意轴对象中,这将非常麻烦(虽然不是不可能)。由于gnovice的解决方案从预先创建的文件中读取字母,所以难以修改代码以对任意颜色方案或字母选择运行。因此,我的解决方案使用了yuk解决方案中的"字母生成"代码和gnovice解决方案中的"图像叠加"方法。
还有大量的参数解析和检查。下面是我的综合解决方案… 我只包括它是为了完整性,显然我不能赢得我的奖励。我将让社区决定奖励,并在时间限制结束时将赏金颁给评分最高的人... 如果打成平局,我会把它给予声誉最低的人(他们可能更需要它)。
function [npos, handle] = SeqLogoFig(SEQ, varargin)
%   SeqLogoFig
%       A function which wraps around the bioinformatics SeqLogo command
%       and creates a figure which is actually a MATLAB figure.  All
%       agruements for SEQLOGO are passed along to the seqlogo calculation.
%       It also supports extra arguements for plotting.
%
%   [npos, handle] = SeqLogoFig(SEQ);
%
%       SEQ             A multialigned set of sequences that is acceptable
%                       to SEQLOGO.
%       npos            The positions that were actually plotted
%       handle          An axis handle to the object that was plotted.
%
%   Extra Arguements:
%       
%       'CUTOFF'        A bit-cutoff to use for deciding which columns to
%                       plot.  Any columns that have a MAX value which is
%                       greater than CUTOFF will be provided.  Defaults to
%                       1.25 for NT and 2.25 for AA.
%
%       'TOP-N'         Plots only the top N columns as ranked by thier MAX
%                       bit conservation.
%
%       'AXES_HANDLE'   An axis handle to plot the seqlogo into.
%       
%       'INDS'          A set of indices to to plot.  This overrides any
%                       CUTOFF or TOP-N that were provided
%
%
%
%

%% Parse the input arguements
ALPHA = 'nt';
MAX_BITS = 2.5;
RES = [200 80];
CUTOFF = [];
TOPN = [];
rm_inds = [];
colors = [];
handle = [];
npos = [];


for i = 1:2:length(varargin)
    if strcmpi(varargin{i}, 'alphabet')
        ALPHA = varargin{i+1};

    elseif strcmpi(varargin{i}, 'cutoff')
        CUTOFF = varargin{i+1};
        %we need to remove these so seqlogo doesn't get confused
        rm_inds = [rm_inds i, i+1]; %#ok<*AGROW>

    elseif strcmpi(varargin{i}, 'colors')
        colors = varargin{i+1};
        rm_inds = [rm_inds i, i+1]; 
    elseif strcmpi(varargin{i}, 'axes_handle')
        handle = varargin{i+1};
        rm_inds = [rm_inds i, i+1]; 
    elseif strcmpi(varargin{i}, 'top-n')
        TOPN = varargin{i+1};
        rm_inds = [rm_inds i, i+1];
    elseif strcmpi(varargin{i}, 'inds')
        npos = varargin{i+1};
        rm_inds = [rm_inds i, i+1];
    end
end

if ~isempty(rm_inds)
    varargin(rm_inds) = [];
end

if isempty(colors)
    colors = GetColors(ALPHA);
end

if strcmpi(ALPHA, 'nt')
    MAX_BITS = 2.5;
elseif strcmpi(ALPHA, 'aa')
    MAX_BITS = 4.5;
end

if isempty(CUTOFF)
    CUTOFF = 0.5*MAX_BITS;
end


%% Calculate the actual seqlogo.
wm = seqlogo(SEQ, varargin{:}, 'displaylogo', false);


%% Generate the letters
letters = wm{1};
letter_wins = cell(size(letters));
[~, loc] = ismember(letters, colors(:,1));
loc(loc == 0) = size(colors,1);
clr = cell2mat(colors(loc, 2)); % corresponding colors
for t = 1:numel(letters)
    hf = figure('position',[200 200 100 110],'color','w');
    ha = axes('parent',hf, 'visible','off','position',[0 0 1 1]);
    ht = text(50,55,letters(t),'color',clr(t,:),'units','pixels',...
        'fontsize',100,'fontweight','norm',...
        'vertical','mid','horizontal','center');
    F = getframe(hf); % rasterize the letter
    img = F.cdata;
    m = any(img < 255,3); % convert to binary image
    m(any(m,2),any(m,1))=1; % mask to cut white borders
    letter_wins{t} = reshape(img(repmat(m,[1 1 3])),[sum(any(m,2)) sum(any(m,1)) 3]);
    close(hf);
end


%% Use the letters to generate a figure

%create a "image" that will hold the final data
wmat = wm{2};
if isempty(npos)
    if isempty(TOPN)
        npos = find(any(wmat>CUTOFF,1));
    else
        [~, i] = sort(max(wmat,[],1), 'descend');
        npos = sort(i(1:TOPN));
    end
end

fig_data = 255*ones(RES(1), RES(2)*(length(npos)+1)+length(npos)*2,3);
bitscores = linspace(0, MAX_BITS, size(fig_data,1));
tick_pos = zeros(length(npos),1);
% place images of letters
for i=1:length(npos)
    [wms idx] = sort(wmat(:,npos(i)), 'descend'); % largest on the top
    bits = [flipud(cumsum(flipud(wms))); 0];
    let_data = letter_wins(idx(wms>0));
    for s=1:length(let_data)
        start_pos = find(bitscores>=bits(s),1);
        end_pos = find(bitscores<=bits(s+1),1, 'last');
        if isempty(start_pos) || isempty(end_pos) || end_pos > start_pos
            continue
        end
        img_win = imresize(let_data{s}, [start_pos-end_pos, RES(2)]);

        fig_data(start_pos-1:-1:end_pos, (i*RES(2)-RES(2)*.5:i*RES(2)+RES(2)*.5-1)+2*i,:) = img_win;
    end
    tick_pos(i) = i*RES(2)+2*i;
end
if ~isempty(handle)
    image(handle,[0 size(fig_data,2)], [0 MAX_BITS],fig_data./255)
else
    handle = image([0 size(fig_data,2)], [0 MAX_BITS],fig_data./255);
end
set(gca, 'ydir', 'normal', 'xtick', tick_pos, ...
        'userdata', tick_pos, 'xticklabel', npos);
xlabel('position')
ylabel('bits')


function colors = GetColors(alpha)
% get the standard colors for the sequence logo
if strcmpi(alpha, 'nt')
    colors = cell(6,2);
    colors(1,:) = {'A', [0 1 0]};
    colors(2,:) = {'C', [0 0 1]};
    colors(3,:) = {'G', [1 1 0]};
    colors(4,:) = {'T', [1 0 0]};
    colors(5,:) = {'U', [1 0 0]};
    colors(6,:) = {'', [1 0 1]};
elseif strcmpi(alpha, 'aa')
    colors = cell(21,2);
    colors(1,:) = {'G', [0 1 0]};
    colors(2,:) = {'S', [0 1 0]};
    colors(3,:) = {'T', [0 1 0]};
    colors(4,:) = {'Y', [0 1 0]};
    colors(5,:) = {'C', [0 1 0]};
    colors(6,:) = {'Q', [0 1 0]};
    colors(7,:) = {'N', [0 1 0]};
    colors(8,:) = {'A', [1 165/255 0]};
    colors(9,:) = {'V', [1 165/255 0]};
    colors(10,:) = {'L', [1 165/255 0]};
    colors(11,:) = {'I', [1 165/255 0]};
    colors(12,:) = {'P', [1 165/255 0]};
    colors(13,:) = {'W', [1 165/255 0]};
    colors(14,:) = {'F', [1 165/255 0]};
    colors(15,:) = {'M', [1 165/255 0]};
    colors(16,:) = {'D', [1 0 0]};
    colors(17,:) = {'E', [1 0 0]};
    colors(18,:) = {'K', [0 0 1]};
    colors(19,:) = {'R', [0 0 1]};
    colors(20,:) = {'H', [0 0 1]};
    colors(21,:) = {'', [210/255 180/255 140/255]};
else
    error('SeqLogoFigure:BADALPHA', ...
            'An unknown alphabet was provided: %s', alpha)
end

我已将此提交给Mathworks FileExchange,一旦获得批准,我会发布链接。
唯一令我困扰的是,在创建字母图像时,它会以快速的速度显示小窗口。如果有人知道可以避免这种情况的技巧,我很想听听。
编辑:Mathworks已经批准了我的提交文件...您可以在FileExchange这里下载:http://www.mathworks.com/matlabcentral/fileexchange/27124

@JudoWill:非常好。关于如何避免出现那些小的图形窗口,我认为你可以在创建它们时将图形窗口的“Visible”属性设置为“off”。 - gnovice
1
@gnovice:如果我没记错的话,getframe需要图形可见。@JudoWill:将字母保存到磁盘可能是个好主意,这样特定字母第一次创建时才会闪现图形。 - Jonas
@Jonas:你可能是对的。我认为他们需要在文档中明确说明这一点,因为我只看到了关于不可见虚拟桌面的提及,而非不可见的图形。 - gnovice
@gnovice:我刚刚测试了一下——getframe确实需要可见的图形。如果它们是不可见的,getframe会将“visible”设置为“on”,这对JudoWill无法解决问题。 - Jonas
如果我能得到一个真正的序列标志图,我可以轻松地忍受一些闪烁的轴。这已经是一个小小的困扰了大约两年时间,最终我终于开始了一个必须要用到真实序列标志图的项目。 - JudoWill
@Jonas:你说得对。我把GETFRAME的行为和PRINT的行为搞混了。即使图形的可见性被关闭,PRINT函数仍然可以将图形保存到文件中。 - gnovice

1
关于x轴,似乎该图不包含标准坐标轴(findobj(handle,'type','axes')为空),而是一个自定义的com.mathworks.toolbox.bioinfo.sequence.SequenceLogo类对象...
另外提一下,你可以用一个更简单的调用来替换你的第一行:
wide_seqs = reshape(randseq(200*500),[],200);

有帮助,但并没有真正回答问题。 - JudoWill

0
如果轴是一个Java对象,那么您可能想使用uiinspect查看其方法和属性。这可能会让您了解应该编辑什么以获得所需的行为(不幸的是,我没有工具箱,所以无法为您查找)。

我使用uiinspect查看了对象...这个Java对象非常稀疏,似乎与轴没有任何关系。我已经向Mathworks提交了支持票据,也许我会有好运。 - JudoWill

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接